gpt4 book ai didi

Python Ctypes 读取从 C++ dll 返回的 char*

转载 作者:行者123 更新时间:2023-11-30 03:25:50 24 4
gpt4 key购买 nike

我发现了 ctypes 的世界,因为我正在使用 C 包装器在 Windows 上用 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* 是必需的参数。

关于Python Ctypes 读取从 C++ dll 返回的 char*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48768161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com