从python中调用C++函数并获取返回值

Call C++ function from python and get return value

本文关键字:获取 返回值 函数 C++ python 调用      更新时间:2023-10-16

我正试图从python脚本中调用C++函数。这是我的示例C++和Python代码。

strfunc.cpp

#include <iostream>
#include <string>
using namespace std;
string getString()
{
string hostname = "test.stack.com";
return hostname;
}

strfunc.py

import ctypes
print(ctypes.CDLL('./strfunc.so').getString())

我使用以下命令从C++程序编译并生成了一个共享库:

g++ -fPIC strfunc.cpp -shared -o strfunc.so

当我尝试执行strfunc.py时,它会给出以下错误:

$ ./strfunc.py 
Traceback (most recent call last):
File "./strfunc.py", line 5, in <module>
print(ctypes.CDLL('./strfunc.so').getString())
File "/usr/lib64/python3.7/ctypes/__init__.py", line 372, in __getattr__
func = self.__getitem__(name)
File "/usr/lib64/python3.7/ctypes/__init__.py", line 377, in __getitem__
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: ./strfunc.so: undefined symbol: getString

请帮我知道如何解决这个问题。int函数也是如此。

如果您在so文件上使用readelf-Ws,它将为您提供so库中的项目:

FUNC全局默认12_Z9getStringB5cxx11v

您将看到您的函数实际上就在那里,它只是有一个损坏的名称。因此,在库上调用ctype的正确名称应该是_Z9getStringB5cxx11v((。

然而,它仍然没有什么问题。将你的方法标记为extern,让编译器知道它有外部链接:

extern string getString()

或者,如果您想将其用作getString((,则可以将其标记为extern"C";这将禁用c++mangler

extern "C" string getString()

但无论哪种情况,我想你都会发现自己有一些记忆问题。我认为正确的方法是将c风格的指针返回到字符数组,并由内存自己管理它,这样的方法应该有效:

strfunc.cpp:

#include <iostream>
#include <string>
using namespace std;
char hostname[] = "test.stack.com";
extern "C" char * getString()
{
return hostname;
}

strfunc.py:

#!/usr/bin/env python
from ctypes import *
test=cdll.LoadLibrary("./strfunc.so")
test.getString.restype=c_char_p
print(test.getString())

在字符串的情况下,我认为您需要弄清楚如何正确管理内存和返回类型,以便让python知道您实际上正在传递字符串。这可能是可行的,但不像上面那样容易。