1

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!

Community
  • 1
  • 1
cas
  • 13
  • 3

1 Answers1

2

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.

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61