tags:

views:

51

answers:

2
+1  Q: 

P/Invoke C# to C++

Hi, 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

A: 

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?

mhutch
I am using mono!
mj_
Yeah, but a normal Mono runtime doesn't contain the Foobar symbol...
mhutch
+1  A: 

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).

lupus