简体   繁体   English

P /将C#调用到C ++

[英]P/Invoke C# to C++

I'm trying to learn how to run C# and C++ code together using Mono on RedHat. 我正在尝试学习如何在RedHat上使用Mono一起运行C#和C ++代码。 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. 我有一个问题,我正在从C#到我的C ++代码进行P / Invoke调用,并且抛出异常。 Using Mono, I can get the C++ code to call the C# code no problem. 使用Mono,我可以获取C ++代码来调用C#代码。

My C++ method that I want the C# to call is as follows. 我希望C#调用的C ++方法如下。

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

My C# code that I have uses the following P/Invoke lines. 我拥有的C#代码使用以下P / Invoke行。

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

In my C# program, I call 在我的C#程序中,我调用

Foobar();

further down in a function. 在功能上进一步下降。 The exception I catch is an EntryPointNotFound exception. 我捕获的异常是EntryPointNotFound异常。 I'm probably overlooking something silly. 我可能忽略了一些愚蠢的事情。

I've used http://www.mono-project.com/Embedding_Mono as instructions regarding how to do this. 我已经使用http://www.mono-project.com/Embedding_Mono作为有关如何执行此操作的说明。

Any suggestions appreciated. 任何建议表示赞赏。 Thanks, 谢谢,

mj MJ

Are you using embedding (that is, you build your own executable that inits the mono runtime)? 您是否正在使用嵌入(即,构建自己的可执行文件以启动Mono运行时)? 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 nm your_program | grep Foobar

and see if a symbol with that name is present in the executable your_program. 并查看可执行文件your_program中是否存在具有该名称的符号。 If you see a mangled name it means extern "C" was not applied correctly in your code. 如果看到名称乱码,则表示在代码中未正确应用extern“ C”。

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). 如果您不使用嵌入,则需要使用动态库名称,而不是DllImport中的__Internal(并检查拼写错误和上述链接器优化问题)。

Why "__Internal"? 为什么是“ __内部”? That's for P/Invoking symbols in the Mono runtime or the program embedding the Mono runtime. 那是为了在Mono运行时或嵌入Mono运行时的程序中使用P /调用符号。 How is your C++ code being compiled and linked? 您的C ++代码如何被编译和链接?

I saw this exact problem, objdump -T and objdump -t differed on the host binary. 我看到了这个确切的问题,objdump -T和objdump -t在主机二进制文件上有所不同。
It was missing the 'D' flag, which means add a -rdynamic to the gcc linker. 它缺少'D'标志,这意味着向gcc链接器添加-rdynamic。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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