Python和ctypes:如何正确传递“ pointer-to-pointer”进入DLL? [英] Python and ctypes: how to correctly pass "pointer-to-pointer" into DLL?
问题描述
我有一个分配内存并返回它的DLL。 DLL中的功能如下:
I have a DLL that allocates memory and returns it. Function in DLL is like this:
void Foo( unsigned char** ppMem, int* pSize )
{
* pSize = 4;
* ppMem = malloc( * pSize );
for( int i = 0; i < * pSize; i ++ ) (* ppMem)[ i ] = i;
}
此外,我有一个python代码,可从我的DLL访问此函数: / p>
Also, i have a python code that access this function from my DLL:
from ctypes import *
Foo = windll.mydll.Foo
Foo.argtypes = [ POINTER( POINTER( c_ubyte ) ), POINTER( c_int ) ]
mem = POINTER( c_ubyte )()
size = c_int( 0 )
Foo( byref( mem ), byref( size ) ]
print size, mem[ 0 ], mem[ 1 ], mem[ 2 ], mem[ 3 ]
我希望 print
将显示 4 0 1 2 3,但它显示 4 221 221 221 221 O_O。任何提示我在做什么
I'm expecting that print
will show "4 0 1 2 3" but it shows "4 221 221 221 221" O_O. Any hints what i'm doing wrong?
推荐答案
发布实际代码。C/ C ++代码无法编译为C或C ++。Python代码具有语法错误(使函数调用Foo终止)。下面的代码有效。修复语法和编译器错误后的主要问题是声明函数 __ stdcall
,因此 windll
可以在Python代码中使用。另一个选择是使用 __ cdecl
(通常是de错误),并在Python代码中使用 cdll
而不是 windll
。
Post actual code. The C/C++ code doesn't compile as either C or C++. The Python code has syntax errors (] ending function call Foo). The code below works. The main issue after fixing syntax and compiler errors was declaring the function __stdcall
so windll
could be used in the Python code. The other option is to use __cdecl
(normally the default) and use cdll
instead of windll
in the Python code.
#include <stdlib.h>
__declspec(dllexport) void __stdcall Foo(unsigned char** ppMem, int* pSize)
{
char i;
*pSize = 4;
*ppMem = malloc(*pSize);
for(i = 0; i < *pSize; i++)
(*ppMem)[i] = i;
}
demo.py
demo.py
from ctypes import *
Foo = windll.mydll.Foo
Foo.argtypes = [POINTER(POINTER(c_ubyte)),POINTER(c_int)]
mem = POINTER(c_ubyte)()
size = c_int(0)
Foo(byref(mem),byref(size))
print size.value,mem[0],mem[1],mem[2],mem[3]
输出
Output
4 0 1 2 3
这篇关于Python和ctypes:如何正确传递“ pointer-to-pointer”进入DLL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!