簡體   English   中英

Python Ctypes 讀取從 C++ dll 返回的 char*

[英]Python Ctypes read char* returned from C++ dll

我正在探索 ctypes 的世界,因為我正在 Windows 上用 C++ 編寫一個帶有 C 包裝器的 DLL,以便能夠在 Python 上使用它。 當我從 C++ 函數返回例如 char * 時,我不明白它如何處理 Python 上的指針,如何獲取指針地址處的數據?

myClass.h文件:

#include "myClassInc.h"
class __declspec(dllexport) myClass// __declspec to generate .lib file
{
public:
    // Attributes
    char * name;

    // Methods
    myClass();
    ~myClass();

    bool myMethod(string);
};

myClassInc.h (C 包裝器):

#ifdef MYCLASS
#  define EXPORT __declspec(dllexport)
#else
#  define EXPORT __declspec(dllimport)
#endif

// Wrapper in C for others languages (LabVIEW, Python, C#, ...)
extern "C"
{
    EXPORT typedef struct myClass myClass; // make the class opaque to the wrapper
    EXPORT myClass* cCreateObject(void);
    EXPORT char* cMyMethod(myClass* pMyClass);
}

myClass.cpp

#include "myClass.h"

myClass::myClass() {}
myClass::~myClass() {}

bool myClass::myMethod(string filename_video)
{
    int iLength = filename_video.length();
    name = new char[iLength+1];
    strcpy(name, filename_video.c_str());
    return true;
}

myClass* cCreateObject(void)
{
    return new myClass();
}

char * cMyMethod(myClass* pMyClass)
{
    if (pMyClass->myMethod("hello world"))
        return pMyClass->name;
}

最后pythonScript.py

from ctypes import *

mydll = cdll.LoadLibrary("mydll.dll")
class mydllClass(object):
    def __init__(self):
        mydll.cCreateObject.argtypes = [c_void_p]
        mydll.cCreateObject.restype = c_void_p

        mydll.cMyMethod.argtypes = [c_void_p]
        mydll.cMyMethod.restype = POINTER(c_char_p)

        self.obj = mydll.cCreateObject("")

    def myMethod(self):
        return mydll.cMyMethod(self.obj)

f = mydllClass() # Create object
a = f.myMethod() # WANT HERE TO READ "HELLO WORLD"

a 中的結果是<__main__.LP_c_char_p object at 0x0000000002A4A4C8>

我沒有在 ctypes 文檔中找到如何讀取這樣的指針數據。 你能幫我嗎?

如果我想從 Python 傳遞一個 char * 到 myDll,將出現同樣的問題,如何做到這一點(通常是在 dll 中提供從 Python 讀取的文件路徑)。

c_char_p是一個char* POINTER(c_char_p)是一個char** 修復你的.restype ,你應該很好。 ctypes具有將c_char_p轉換為 Python 字節字符串的默認行為。

此外, mydll.cCreateObject.argtypes = None對於沒有參數是正確的。 現有定義指出void*是必需參數。

暫無
暫無

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

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