Skip to content Skip to sidebar Skip to footer

Assigning Python Function To Ctypes Pointer Variable

I have the following C source that I compile into a DLL: int (*pfuncExtB)(int a, int b); int funcB(int a, int b) { return funcExtB(a, b); } int funcExtB(int a, int b) { r

Solution 1:

The correct type of the global variable in Python is CFUNCTYPE(c_int,c_int,c_int) (no POINTER()), but I don't see a method to change the value of the variable once you have it. If you can add a set function it can work:

C

typedefint(*FUNC)(int,int);

__declspec(dllexport) FUNC pfuncExtB;

__declspec(dllexport) voidset(FUNC f){
    pfuncExtB = f;
}

intfuncExtB(int a, int b){
    returnpfuncExtB(a, b);
}

__declspec(dllexport) intfuncB(int a, int b){
    returnfuncExtB(a, b);
}

Python

from ctypes import *

FUNC = CFUNCTYPE(c_int,c_int,c_int)

@FUNCdefadd(a, b):
    return a + b

mutdll = cdll.LoadLibrary('x')

mutdll.set.argtypes = [FUNC]
mutdll.set.restype = None

mutdll.set(add) # set the global variable

pfuncExtB = FUNC.in_dll(mutdll,'pfuncExtB')
print(pfuncExtB(1,2)) # -> 3

funcB = mutdll.funcB
funcB.argtypes = [c_int, c_int]
funcB.restype = c_int

print(funcB(3 , 4)) # -> 7

Note that this does not work:

pfuncExtB = POINTER(FUNC).in_dll(mutdll,'pfuncExtB')
pfuncExtB.contents(1,2) # exception!

Post a Comment for "Assigning Python Function To Ctypes Pointer Variable"