ctypes - 从 C++ 函数获取输出到 python 对象

ctypes - get output from c++ function into python object

我已经按照此处给出的第二个答案中的示例代码进行操作 - 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'

所以,即使参数不同,也是一样的。我在这里错过了什么?

@Paul Mu Guire 上面的建议可能有所帮助,但我需要的是一些非常简单的东西,它接受一个字符串并输出一个字符串。因此,整个面向对象的范式是矫枉过正的。我改为简单的 C 结构 -

extern "C" {
char* linked(char * in){ 
    return in;
  }
}

并且在执行 lib.linked.restype = c_char_p 之后效果很好。