Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ctypes addressof CFuncType

Tags:

python

ctypes

Related to my other question

How can I get the address (acctual function pointer) to a CFuncType object? addressof() does not report the correct address.

C code:

extern "C" _declspec(dllexport)
int addr(int (*func)())
{
    int r = (int)func;
    return r;
}

Python code:

def test():
  return 42

t = CFUNCTYPE(c_int)
f = t(test)

print addressof(f)
print dll.addr(f)

Output:

7030864
3411932

trying to call *(7030864) from C causes a crash, but calling *(3411932) works as expected. What's wrong with addressof()?

like image 709
Knio Avatar asked Jan 10 '10 22:01

Knio


People also ask

What is ctypes in Python?

ctypes — A foreign function library for Python¶. ctypes is a foreign function library for Python. It provides C compatible data types, and allows calling functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python.

What is cfunctype in C?

ctypes. CFUNCTYPE (restype, *argtypes, use_errno=False, use_last_error=False) ¶ The returned function prototype creates functions that use the standard C calling convention.

What is the default C int type in Python?

Python integers and Python longs are passed as the platforms default C int type, their value is masked to fit into the C type. Before we move on calling functions with other parameter types, we have to learn more about ctypes data types. ctypes defines a number of primitive C compatible data types :

How do I call a C function from a python function?

ctypes allows creating C callable function pointers from Python callables. These are sometimes called callback functions. First, you must create a class for the callback function. The class knows the calling convention, the return type, and the number and types of arguments this function will receive.


1 Answers

cast(f, c_void_p) gets the correct address from within python

like image 114
Knio Avatar answered Sep 22 '22 06:09

Knio