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!

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot Paul, it solves the issue! appreciate your help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.