简体   繁体   English

Python和ctypes:如何正确地将“指针指针”传递给DLL?

[英]Python and ctypes: how to correctly pass “pointer-to-pointer” into DLL?

I have a DLL that allocates memory and returns it. 我有一个DLL分配内存并返回它。 Function in DLL is like this: DLL中的函数是这样的:

void Foo( unsigned char** ppMem, int* pSize )
{
  * pSize = 4;
  * ppMem = malloc( * pSize );
  for( int i = 0; i < * pSize; i ++ ) (* ppMem)[ i ] = i;
}

Also, i have a python code that access this function from my DLL: 另外,我有一个从我的DLL访问此函数的python代码:

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 ]

I'm expecting that print will show "4 0 1 2 3" but it shows "4 221 221 221 221" O_O. 我期待print将显示“4 0 1 2 3”,但它显示“4 221 221 221 221”O_O。 Any hints what i'm doing wrong? 什么提示我做错了什么?

Post actual code. 发布实际代码。 The C/C++ code doesn't compile as either C or C++. C / C ++代码不能编译为C或C ++。 The Python code has syntax errors (] ending function call Foo). Python代码有语法错误(]结束函数调用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. 修复语法和编译器错误后的主要问题是声明函数__stdcall因此可以在Python代码中使用windll The other option is to use __cdecl (normally the default) and use cdll instead of windll in the Python code. 另一种选择是使用__cdecl (通常是默认值)并在Python代码中使用cdll而不是windll

mydll.c (cl /W4 /LD mydll.c) mydll.c(cl / W4 / LD mydll.c)

#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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM