Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

python - Access violation when using ctypes callback feature

I'm trying to use the ctypes callback feature to pass a python function to a C function as a function pointer. Here's the C:

typedef void(*f1)();

void function_that_takes_a_function(f1* fn){
    printf("I'm a function that takes a function
");
    double d1[2] = {0.1, 0.2} ;
    printf("1
");
    double *d2;
    printf("2
");
    double *g;
    printf("3
");

    printf("%d
", (long )fn);

    (*fn)(); 
    printf("4
");
}

And the Python

        import ctypes as ct

        lib = ct.CDLL("SRES")
        F1_CALLBACK = ct.CFUNCTYPE(None)
        function_that_takes_a_function = lib.function_that_takes_a_function
        function_that_takes_a_function.argtypes = [F1_CALLBACK]
        function_that_takes_a_function.restype = None

        @F1_CALLBACK
        def func_to_pass_in():
            print("hello from Python")

        function_that_takes_a_function(func_to_pass_in)

This gives me

I'm a function that takes a function
1
2
3
-1788276848

Error
Traceback (most recent call last):
  File "C:Miniconda3envspy38libunittestcase.py", line 60, in testPartExecutor
    yield
  File "C:Miniconda3envspy38libunittestcase.py", line 676, in run
    self._callTestMethod(testMethod)
  File "C:Miniconda3envspy38libunittestcase.py", line 633, in _callTestMethod
    method()
  File "Guassianproblem.py", line 77, in testFunctionPointerInIsolation
    function_that_takes_a_function(func_to_pass_in)
OSError: exception: access violation writing 0xFFFFFFFFF9158D4C

Where I expect to see:

I'm a function that takes a function
1
2
3
Hello from Python 
4

Can anybody spot my problem?

question from:https://stackoverflow.com/questions/65907627/access-violation-when-using-ctypes-callback-feature

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

f1 is already a pointer to a function with return type void and no parameter (see type definition). The following works.

typedef void(*f1)();
    
void function_that_takes_a_function(f1 fn)
{
  fn();
}

with the following Python code:

        import ctypes as ct

        lib = ct.CDLL("SRES")
        F1_CALLBACK = ct.CFUNCTYPE(None)
        function_that_takes_a_function = lib.function_that_takes_a_function
        function_that_takes_a_function.argtypes = [F1_CALLBACK]
        function_that_takes_a_function.restype = None

        @F1_CALLBACK
        def func_to_pass_in():
            print("hello from Python")

        function_that_takes_a_function(func_to_pass_in)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...