简体   繁体   中英

P/Invoke C# to C++

I'm trying to learn how to run C# and C++ code together using Mono on RedHat. I'm fooling around in order to learn how to get the two to interoperate together in order to be a bit more educated when I work on a larger project.

I've got a problem that I'm making a P/Invoke call from the C# to my C++ code and an exception is being thrown. Using Mono, I can get the C++ code to call the C# code no problem.

My C++ method that I want the C# to call is as follows.

extern "C"{
    void Foobar(){
         printf("Hooray!");
    }
}

My C# code that I have uses the following P/Invoke lines.

[DllImport ("__Internal", EntryPoint="Foobar")]
static extern void Foobar();

In my C# program, I call

Foobar();

further down in a function. The exception I catch is an EntryPointNotFound exception. I'm probably overlooking something silly.

I've used http://www.mono-project.com/Embedding_Mono as instructions regarding how to do this.

Any suggestions appreciated. Thanks,

mj

Are you using embedding (that is, you build your own executable that inits the mono runtime)? In that case the possibilitites are usually two:

  • You have a typo
  • The compiler/linker removed during optimization the function from your binary

To check for either, run:

nm your_program |grep Foobar

and see if a symbol with that name is present in the executable your_program. If you see a mangled name it means extern "C" was not applied correctly in your code.

If you're not using embedding, you need to use the dynamic library name and not __Internal in DllImport (and check for typos and the above linker optimization issue as well).

Why "__Internal"? That's for P/Invoking symbols in the Mono runtime or the program embedding the Mono runtime. How is your C++ code being compiled and linked?

I saw this exact problem, objdump -T and objdump -t differed on the host binary.
It was missing the 'D' flag, which means add a -rdynamic to the gcc linker.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM