Search code examples
cc++11dynamic-library

Calling C++ Application Code from C library?


Folks, Assuming I have a c++ application / library running which implements say

/* Alloc API */
void* my_alloc(int size) {
    return malloc(sizeof(size));
}

This is not under "extern c".

I have a C dynamic library from which I need to call my_alloc, can I directly call that API?

Like,

int test_my_alloc (int size) {
    int *x;

    x = (int*)my_alloc(size);
    if (x == NULL) {
        return 0;
    } else {
        return 1;
    }
}

Solution

  • You need to create a stub, e.g.

    Stub header:

    // stub.h
    
    #ifdef __cplusplus
    extern "C" {
    #endif
    
    void* my_alloc_c(int size);
    
    #ifdef __cplusplus
    }
    #endif
    

    Stub implementation:

    // stub.cpp
    
    #include "stub.h"
    #include "header_where_my_alloc_is_declared.h"
    
    void* my_alloc_c(int size)
    {
        return my_alloc(size);
    }
    

    Your C code (example):

    // my_code.c
    
    #include "stub.h"
    
    int main()
    {
        void * p = my_alloc_c(42);
        return 0;
    }
    

    Then compile your stub and link it with your C code:

    g++ -Wall -c stub.cpp          # compile stub.cpp
    gcc -Wall my_code.c stub.o     # compile your C code and link with stub.o