从Python调用C++函数并获得返回值

2024-05-05 19:54:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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++命令编译并生成了一个共享库:< /p>

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函数


Tags: 函数inpyselfstringsoincludeline
1条回答
网友
1楼 · 发布于 2024-05-05 19:54:16

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

FUNC GLOBAL DEFAULT 12 _Z9getStringB5cxx11v

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

然而,它仍然有一些问题。 将您的方法标记为外部,让编译器知道它具有外部链接:

extern string getString()

可选地,如果你想用它作为GESTSTRAGE(),你可以把它标记为Extn“C”,它将禁用C++ Mangeler-

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知道您实际上在传递字符串。这可能是可行的,但不像上面那样容易

相关问题 更多 >