在python中如何设置LP_c_ubyte的值 [英] In python how do I set the value of a LP_c_ubyte
问题描述
我正在使用python ctypes为C DLL创建Python包装器。我无法使用python更新指向内存中值的指针。
I am creating a Python wrapper for a C DLL using python ctypes. I am having trouble updating a pointer to value in memory with python.
在此示例中,我有一个具有注册回调函数的DLL。调用回调函数将创建无符号char变量,将指向该变量的指针传递给回调函数,然后输出该变量的更新值。
In this example I have a DLL that has a register callback function. A invoke callback function that creates unsigned char variable, passes a pointer to that variable to the callback function, then prints the updated value of that variable.
我希望发生的是python函数 callbackUpdateValue
将更新的值foo
,更新后的值将打印在C DLL DoCallBack
函数中。将打印 0
的值,而不是预期的 99
What I expected to happen is that the python function callbackUpdateValue
would update the value of foo
, and the updated value would be printed in C DLL DoCallBack
function. The value of 0
is printed instead of the expected value of 99
我的问题是:在python中,如何在 callbackUpdateValue $ c中更新
foo
的值$ c>以便可以将其打印在C DLL DoCallBack
函数中?
My question is: In python how do I update the value of foo
in callbackUpdateValue
so that it can be printed in the C DLL DoCallBack
function?
我已将代码最小化为
DLL C ++代码
DLL具有两个功能。一个注册一个回调,另一个调用回调并打印结果。
The DLL has two functions. One to register up a callback, the other to invoke the callback and print the results.
#include <stdio.h>
typedef void(*FPCallback)(unsigned char * foo);
FPCallback g_Callback;
extern "C" __declspec( dllexport ) void RegisterCallback(void(*p_Callback)(unsigned char * foo)) {
g_Callback = p_Callback ;
}
extern "C" __declspec( dllexport ) void DoCallBack() {
unsigned char foo = 0 ;
g_Callback( &foo );
printf( "foo=%d\n", foo);
}
Python代码
Python代码设置了回调函数,然后从DLL调用DoCallBack函数。
The python code sets up the call back function, then calls the DoCallBack function from the DLL.
from ctypes import *
def callbackUpdateValue( foo ):
foo = 99
customDLL = cdll.LoadLibrary ("customeDLL.dll")
# RegisterCallback
CustomDLLCallbackFUNC = CFUNCTYPE(None, POINTER( c_ubyte))
CustomDLLCallback_func = CustomDLLCallbackFUNC( callbackUpdateValue )
RegisterCallback = customDLL.RegisterCallback
RegisterCallback.argtypes = [ CustomDLLCallbackFUNC ]
RegisterCallback( CustomDLLCallback_func )
# DoCallBack
DoCallBack = customDLL.DoCallBack
# Call the callback
DoCallBack()
推荐答案
定义python回调的正确方法是
The correct way to define the python callback is
def callbackUpdateValue( foo ):
foo[0] = 99
其中 foo [0]
取消引用指针。可在此处找到更多信息: https://docs.python.org /2.5/lib/ctypes-callback-functions.html
where foo[0]
dereferences the pointer. More info can be found here: https://docs.python.org/2.5/lib/ctypes-callback-functions.html
这篇关于在python中如何设置LP_c_ubyte的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!