简体   繁体   English

P /调用C#和本机C ++

[英]P/Invoke c# and native c++

My c# is really bad, and I'll get a book or something to improve it later on. 我的C#确实很糟糕,以后我会买一本书或进行一些改进。 Right now, I have a gui in c# wpf and a dll library in native c++. 现在,我在c#wpf中有一个gui,在本机c ++中有一个dll库。 All the tutorials I see on the internet for p/invoke don't have classes in them. 我在网上看到的所有有关p / invoke的教程都没有课程。

Here's what my code looks like in c++: 这是我的代码在c ++中的样子:

//Dostuff.h

class foo {
__declspec(dllexport) void dostuff();
 }

How would I go about calling the dll from c#? 我将如何从c#调用dll? Thanks in advance. 提前致谢。

A C++ library without wrappers is often useless outside of the C++ compiler that built it. 没有包装器的C ++库在构建它的C ++编译器之外通常是无用的。 C# won't make using such a library easy for you...and even if you manage to do it, things may break in all kinds of interesting ways. C#会让您不容易使用这样的库...即使您设法做到这一点,事情也可能以各种有趣的方式破裂。

You have two relatively safe choices, though: 但是,您有两个相对安全的选择:

  • Export a set of extern "C" wrapper functions in your library. 在您的库中导出一组extern "C"包装函数。 You'd take a pointer to the object you want to use, and call a function on that object. 您将获得一个指向要使用的对象的指针,并在该对象上调用一个函数。 If you go that route, it's about as close as you can get to universally compatible; 如果您走这条路,那么它与通用兼容性就差不多了。 any language that can call C functions will be able to use the library. 任何可以调用C函数的语言都可以使用该库。
  • If you're using Visual C++, you can do something similar specifically for .net. 如果您使用的是Visual C ++,则可以专门针对.net执行类似的操作。 Write a wrapper in C++/CLI that compiles for .net, but forwards calls to the native library. 在C ++ / CLI中编写一个包装程序,该包装程序可以为.net进行编译,但是会将调用转发给本机库。

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

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