从python中调用C++函数并获取返回值
Call C++ function from python and get return value
我正试图从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知道您实际上正在传递字符串。这可能是可行的,但不像上面那样容易。
相关文章:
- 从python中调用C++函数并获取返回值
- 调用CreateProcess()并获取字符串的返回值
- 如何将不可移动和不可复制的函数返回值获取到数组中
- 如何在 c++ 窗口中将参数和返回的退出值传递到批处理文件/从批处理文件获取返回的退出值
- 如何在 c++ 中使用 future 和 promise 从函数线程中获取返回值
- 从 Freeglut/Opengl 2.1 项目中获取返回值
- 如何从 CreateThread() 中加载的函数中获取返回值?
- Boost::ASIO:如何从io_service中获取返回值
- 关于如何在函数执行后使用和获取返回值的问题
- 如何在关机调用后在 UDP recvfrom() 调用中获取返回值 0
- 无法获取返回值
- 如何从调用的函数获取返回值,该函数在 TBB 中的另一个线程中执行
- 从 MFC(c++) 应用程序启动的可执行 jar 中获取返回值
- 如何在 c++ 中从函数获取返回值而不为其变量赋值
- 传递对象并从线程调用中获取返回值
- 如何从 QMetaObject::invokeMethod 获取返回值
- 在C++中获取返回值的类型
- 如何获取返回值并将其设置为 "x" ?
- pthread_create(),如何从传递的函数中获取返回值
- 稍后从线程函数中获取返回值