簡體   English   中英

從 python 調用 C++ function 並獲取返回值

[英]Call C++ function from python and get return value

我正在嘗試從 python 腳本調用 C++ function 。 這是我的示例 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 function。

如果您在 so 文件上使用 readelf -Ws,它將在 so 庫中為您提供項目:

FUNC 全局默認值 12 _Z9getStringB5cxx11v

你會看到你的 function 實際上在那里,它只是有一個錯誤的名稱。 因此,在庫上調用 ctype 的正確名稱是 _Z9getStringB5cxx11v()。

但是,它仍然有一些問題。 將您的方法標記為外部,讓編譯器知道它具有外部鏈接:

extern string getString()

或者,如果您想將其用作 getString(),您可以將其標記為 extern "C",這將禁用 c++ mangler

extern "C" string getString()

但無論哪種情況,我想你都會發現你有一些 memory 問題。 我認為正確的方法是將 c 樣式指針返回到字符數組,然后 memory 自己管理它,這樣的事情應該可以工作:

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())

如果是字符串,我認為您需要弄清楚如何管理 memory 並正確返回類型,以便讓 python 知道您實際上是在傳遞字符串。 這可能是可行的,但不像上面那么容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM