【发布时间】:2016-07-03 08:38:43
【问题描述】:
我已按照此处给出的第二个答案中的示例代码 - Calling C/C++ from python?
并设法让它接受一个字符串参数。
这是我修改后的 cpp 文件:
#include <iostream>
using namespace std;
class Foo{
public:
char* bar(char in[1000]){
std::cout << "Hello" << std::endl;
std::cout << in << std::endl;
return in;
}
};
extern "C" {
Foo* Foo_new(){ return new Foo(); }
char* Foo_bar(Foo* foo, char in[1000]){ return foo->bar(in); }
}
然后我的python函数看起来像这样 -
from ctypes import cdll
lib = cdll.LoadLibrary('./libfoo.so')
class Foo(object):
def __init__(self):
self.obj = lib.Foo_new()
def bar(self, st):
lib.Foo_bar(self.obj, st)
f = Foo()
a = f.bar('fd')
这会在屏幕上打印“Hello”和“fd”,但是当我查看 a 时,它是空的。如何修改此代码,以便将结果输入 python 对象,a?
编辑:基于我在这里指出的另一个问题,How to handle C++ return type std::vector<int> in Python ctypes?
我尝试了以下方法:
from ctypes import *
lib.Foo_bar.restype = c_char_p
a=lib.Foo_bar('fff')
这给出了 - '\x87\x7f'
a = lib.Foo_bar('aaa')
这给出了 - '\x87\x7f'
所以,即使论点不同,也一样。我在这里想念什么?
【问题讨论】:
-
lib.Foo_bar.restype = c_char_pper docs.python.org/2/library/ctypes.html#return-types -
另外,对于 Python3,你可能想关注stackoverflow.com/questions/17434977/…
-
大喊是
return lib.Foo_bar(self.obj, st)? -
您可能还需要这些:
lib.Foo_new.restype = c_void_p; lib.Foo_bar.argtypes = [c_void_p, c_char_p]