返回C ++ double到Python? [英] Return C++ double to Python?

查看:798
本文介绍了返回C ++ double到Python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我使用python在共享的C ++库中调用方法。我有一个问题从C ++返回一个双重的python。我有一个玩具示例展示了这个问题。



这里是python代码(soexample.py):

 #Python从ctypes导入
import CDLL
import numpy as np

#打开共享CPP库:
cpplib = CDLL './libsoexample.so')
cppobj = cpplib.CPPClass_py()

#转换为短**?
x = cpplib.func_py(cppobj)
print'x =',x

这里是C ++(soexample.cpp):

  #include< iostream> 

using namespace std;

class CPPClass
{
public:
CPPClass(){}

void func(double& x)
{
x = 1.0;
}
};

//用于python:
externC{
CPPClass * CPPClass_py(){return new CPPClass(); }
double func_py(CPPClass * myClass)
{
double x;
myClass-> func(x);
return x;
}
}

编译:

  g ++ -fPIC -Wall -Wextra -shared -o libsoexample.so soexample.cpp 

当我运行时我得到:

  $ python soexample.py 
x = 0

因此结果是类型为整数,值为0.发生了什么? / p>

我也很好奇通过引用填充数组。

解决方案

ctypes文档


默认情况下,函数返回C int 类型。其他
返回类型可以通过设置
函数对象的 restype 属性来指定。


如果您将 func_py 的使用更改为以下内容,则此方法有效:

  import ctypes 

func_py = cpplib.func_py
func_py.restype = ctypes.c_double
x = func_py(cppobj)
print 'x =',x

虽然它可能适用于这种简单的情况, code> CPPClass_py.restype 。


So I am using python to call methods in a shared C++ library. I am having an issue returning a double from the C++ to the python. I have a created a toy example that exhibits the problem. Feel free to compile and try it out.

Here is the python code (soexample.py):

# Python imports
from ctypes import CDLL
import numpy as np

# Open shared CPP library:
cpplib=CDLL('./libsoexample.so')
cppobj = cpplib.CPPClass_py()

# Stuck on converting to short**?
x = cpplib.func_py(cppobj)
print 'x =', x

Here is the C++ (soexample.cpp):

#include <iostream>

using namespace std;

class CPPClass
{
  public:
  CPPClass(){}

  void func(double& x)
  {
    x = 1.0;
  }
};

// For use with python:
extern "C" {
    CPPClass* CPPClass_py(){ return new CPPClass(); }
    double func_py(CPPClass* myClass)
    {      
      double x;  
      myClass->func(x);
      return x;    
    }
}

Compile with:

g++ -fPIC -Wall -Wextra -shared -o libsoexample.so soexample.cpp

When I run I get:

$ python soexample.py
x = 0

So the result is an integer in type and of value 0. What's going on?

I'm also curious about filling arrays by reference.

解决方案

From ctypes documentation:

By default functions are assumed to return the C int type. Other return types can be specified by setting the restype attribute of the function object.

It works if you change your use of func_py to the following:

import ctypes

func_py = cpplib.func_py
func_py.restype = ctypes.c_double
x = func_py(cppobj)
print 'x =', x

While it will probably work for this simple case, you should also specify CPPClass_py.restype as well.

这篇关于返回C ++ double到Python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆