Akamai
Akamai

Reputation: 117

Provide external definition of function with ctypes to a C/C++ library

I have a simple library that uses a function hello_printf(const char *format, ...) in one of its API. While using this library in C, I point the function pointer of hello_printf to printf in the external application using the library and code works seamlessly.

hello_printf is not the API but is used in the implementation of one of the API's. The reason for this is that I want external application using the library to provide implementation of printf (external binding).

Now I want to use this library in python and I am using ctypes to call the API's but I am unable to find a way to find the provide external binding of function with ctypes. i.e. point hello_printf() to printf of libc such that "hello_printf = libc.printf ".

Upvotes: 3

Views: 442

Answers (1)

Eryk Sun
Eryk Sun

Reputation: 34260

You're looking for the in_dll method of ctypes data types.

C:

#include <stdlib.h>

int (*hello_printf)(const char *format, ...) = NULL;

int test(const char *str, int n) {
    if (hello_printf == NULL)
        return -1;
    hello_printf(str, n);
    return 0;
}

ctypes:

from ctypes import *

cglobals = CDLL(None)
lib = CDLL("./lib.so")

hello_printf = c_void_p.in_dll(lib, "hello_printf")
hello_printf.value = cast(cglobals.printf, c_void_p).value

>>> lib.test("spam %d\n", 1)
spam 1
0

Upvotes: 3

Related Questions