Home > Mobile >  Make alias to C types in C namespace
Make alias to C types in C namespace

Time:11-08

I have a DLL in pure C code. I would like to find a way to remove the library name prefix from the functions, classes, and structs; EX:

// lib.h
void foobar();
// lib.hpp
namespace foo {
    bar();
}

I would like to avoid simply writing a wrapper for every function, since I'd have to write it for every time I want to add a function. Is there a better / more efficient way of writing this?

I started writing the wrapper idea, but there's a lot of functions to write this for. Void pointers worked a little better, but still had the same issue.

CodePudding user response:

Unless you are worried about name conflicts between existing C function names and the C library, how about just declaring the C function extern "C" (in your C code) and call it (from your C or C code). For example:

extern "C" void f(int); // apply to a single function
extern "C" {    // or apply to a block of functions
    int g(double);
    double h(void);
};
void code(int i, double d)
{
    f(i);
    int ii = g(d);
    double dd = h();
    // ...
}

When code is enclosed within an extern “C” block, the C compiler ensures that the function names are un-mangled – that the compiler emits a binary file with their names unchanged, as a C compiler would do.
This approach is commonly used to accommodate inter language linkage between C and C.

from this Reference
more from cppprefference.com

CodePudding user response:

You could try this:

// lib.hpp
namespace foo {
    constexpr auto bar = foobar;
}

This should create a function pointer, and because it is constexpr, it should get resolved at compile time, so no performance hit. Also, constexpr is implicitly inline, so that (or static) can be omitted from this definition.

  • Related