Reputation: 13
I am writing a test script in Python to call C functions using ctypes ctypes - Beginner
I have a list of functions and the corresponding shared object names and need to call these functions dynamically using python script.
While I use it to directly call the function name in Python script, it works just fine and prints "hello world" on terminal!
Python Script:
import ctypes
import os
sharedObjectPath = (os.getcwd() + "/" + "sharedObject.so")
test = ctypes.CDLL(sharedObjectPath)
test.printHello()
C code:
#include < stdio.h>
void printHello(void);
void printHello()
{
printf("hello world\n");
}
However, it throws an error while trying to use a variable to load the function name:
Python Script: (Dynamic function call)
import ctypes
import os
sharedObjectPath = (os.getcwd() + "/" + "sharedObject.so")
test = ctypes.CDLL(sharedObjectPath)
fName = "printHello()"
test.fName
Error: "complete path"/sharedObject.so: undefined symbol: fName
Any help and suggestions are deeply appreciated! thanks!
Upvotes: 1
Views: 792
Reputation: 21619
To invoke the function using it's name as a string, you this can do this
...
fName = "printHello"
test[fName]()
So the functions name (minus the ()
) is used to index into the module object and after that it's invoked.
Upvotes: 2