Python Ctypes read char*从C++;动态链接库 我发现了CyType的世界,因为我在C++上用C++编写了一个DLL,可以在Python上使用它。当我从我的C++函数返回一个char *,如何在指针的地址处获取数据时,我不理解指针在Python上的作用。

Python Ctypes read char*从C++;动态链接库 我发现了CyType的世界,因为我在C++上用C++编写了一个DLL,可以在Python上使用它。当我从我的C++函数返回一个char *,如何在指针的地址处获取数据时,我不理解指针在Python上的作用。,python,c++,ctypes,Python,C++,Ctypes,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包装):

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包装):

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"
结果是

我在ctypes文档中找不到如何读取这样的指针数据。你能帮我吗


如果我想将一个char*从Python传递到myDll,那么同样的问题也会随之而来,如何做(通常是在dll中给出从Python读取的文件路径)。

c\u char\p
是一个
char*
<代码>指针(c\u char\u p)是一个
字符**
。修正你的
.restype
,你应该很好
ctypes
具有将
c\u char\p
转换为Python字节字符串的默认行为


另外,
mydll.cCreateObject.argtypes=None
对于任何参数都是正确的。现有的定义指出,
void*
是一个必需的参数。

如果我取下
指针
,程序就会崩溃(确切地说是Python),进程以退出代码-1073741819(0xC0000005)结束。当我调用
myMethod
时会发生崩溃。我测试返回了一个整数或布尔值,它正在工作。因此,问题仅限于char*。@MathieuGauquelin提供的示例没有按原样编译(例如缺少
#include
)。在修复错误和删除指针后,它对我起了作用。您必须将代码完全更新为您测试过的代码。同时提供相关的环境细节。我使用了Windows 10、VS2015和Python 3.6(全部为64位)非常感谢。我还成功地使用
c\u char\u p(“mystring.encode('utf-8'))
发送了一个字符串。下一步,获取unsigned short的双指针:D@Mathieu
b'hello'
是如何发送字节字符串的。你不需要用c_char_p包装。
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"