WhatsUp
WhatsUp

Reputation: 1626

C++ link an extern function as member function

Basically, I have an already compiled a file that is written assembly; .obj file. It has an exported function f. In C++, I wrote a class and want to use the exported function f as a member function.

If it were to be used as a global function, I know that one just writesextern "C" f(). However, this doesn't work with a member function, at least I didn't figure out how to do it.

So, how do I do it?

Note: The function f is written properly. i.e. it takes into account the this pointer, etc. It should work correctly at assembly level.

Upvotes: 1

Views: 263

Answers (1)

Adam H. Peterson
Adam H. Peterson

Reputation: 4591

If the function is written as a free function, you will have to declare it as a free function the way you're accustomed to. Just as you can't build a library with void foo() and then somehow declare it as void bar() and expect it to work, you can't take a free function and turn it into a member function. What you can do, though, is add an inline forwarder into your class like so:

struct S;
extern "C" void f( S * );

struct S {
    void f() {
        using ::f;
        f(this);
    }
};

That's the best you can do, as far as I'm aware.

Upvotes: 4

Related Questions