我正在尝试使用Python中的ctypes从dll调用C++函数。我目前的问题是该函数似乎返回一个大整数,无论是正数还是负数,而不是我期望的char指针。如果我将该整数转换为c_char_p并在其上调用.value,则每次都会杀死我的内核。我在这个网站和文档中到处寻找答案,但仍然无法解决这个问题。我在这个网站上看到的很多东西甚至会为我报错,比如向ctypes对象和函数传递字符串时应该是字节对象或类似的内容。以下是我转换为dll的C++代码以及我用于从dll调用函数的Python代码。如果有人能帮助我,那就太棒了。SaySomething是要处理的函数。谢谢。
TestLibrary.h
#pragma once
#ifdef TESTLIBRARY_EXPORTS
#define TESTLIBRARY_API __declspec(dllexport)
#else
#define TESTLIBRARY_API __declspec(dllexport)
#endif
#include <windows.h>
#include <cstring>
#ifdef __cplusplus
extern "C"
{
#endif
TESTLIBRARY_API char* SaySomething(const char* phrase);
#ifdef __cplusplus
};
#endif
TestLibrary.cpp
#include "stdafx.h"
#include "TestLibrary.h"
#include <iostream>
TESTLIBRARY_API char* SaySomething(const char* phrase)
{
char* p = new char [100];
p = "string something";
return p;
}
tester2.py
import ctypes
dbl = ctypes.c_double
pChar = ctypes.c_char_p
pVoid = ctypes.c_void_p
libName = (r"D:\Documents\Coding Stuff\Visual Studio 2017\Projects\TestLibrary"
r"Solution\x64\Debug\TestLibrary.dll")
x = ctypes.windll.LoadLibrary(libName)
x.SaySomething.argtypes = [pChar]
x.SaySomething.restypes = pChar
phrase = b"Hi"
phrase = pChar(phrase)
res = x.SaySomething(phrase)
restype
,而不是restypes
。 - Eryk Sunp = "string something";
可能不会像您想象的那样工作。令人惊讶的是,结果看起来似乎可以正常工作 ;) - ddbugTESTLIBRARY_EXPORTS
时,TESTLIBRARY_API
的定义使用了dllexport
。它应该是dllimport
。这不会影响通过ctypes使用库。但对于C/C++库的用户来说,这是个问题。 - Eryk Sun