[英]How to Interop to C++ with Namespace
I have a C++ function, that I want to expose to C# for consumption. 我有一个C ++函数,我希望将其暴露给C#以供使用。 The catch is that the C++ code declaration is wrapped in namespace : 问题是C ++代码声明包含在命名空间中 :
namespace OhYeahNameSpace
{
extern "C" __declspec(dllexport) void Dummy();
}
My question is, how to define the corresponding C# structure? 我的问题是,如何定义相应的C#结构? I believe that C# code must be made aware of the existence of OhYeahNameSpace
, am I right? 我相信必须让C#代码知道OhYeahNameSpace
的存在,对吗?
Edit: I think a lot of people misunderstand my point ( no thanks due to a typo in my original example; fixed). 编辑:我认为很多人误解了我的观点(不用多谢,因为我原来的例子中有一个拼写错误;已修复)。 I am asking about how to go by if there is a namespace for which the exported function is dwell on. 我问的是如果存在导出函数所针对的命名空间,该如何过去。 One answer are missing on this part, another one says this can't be done and ask me to wrap it around, and another one is now currently with -1 vote. 这一部分缺少一个答案,另一个答案说不能这样做并要求我把它包起来,而另一个现在正在进行-1投票。
Why not wrap in C++/CLI? 为什么不用C ++ / CLI换行?
//ohyeah.h
namespace OhYeahNameSpace
{
public ref class MyClass
{
void Dummy();
}
}
//ohyeah.cpp
#include "ohyeah.h"
namespace OhYeahNameSpace
{
void MyClass::Dummy()
{
// call the real dummy in the DLL
}
}
Wrap as C and use P/Invoke: 换行为C并使用P / Invoke:
--- OhYeahNameSpace_C.h ---
#ifdef __cplusplus
extern "C" {
#endif
void _declspec(dllexport) OhYeahNameSpace_Dummy();
#ifdef __cplusplus
}
#endif
--- OhYeahNameSpace_C.c ---
#include "OhYeahNameSpace_C.h"
#include <OhYeahNameSpace.h>
void OhYeahNameSpace_Dummy()
{
::OhYeahNameSpace::Dummy();
}
The example isn't 100% complete, but you get the gist of it. 这个例子不是100%完整,但你得到了它的要点。
One possible solution would be to use P/Invoke (besides the already mentioned one wrapping in a C++/CLI class 一种可能的解决方案是使用P / Invoke(除了已经提到的C ++ / CLI类中的一个包装)
in C++ (I assume your function is in a project resulting in a DLL named UnmanagedCpp.dll: 在C ++中(我假设你的函数在一个项目中导致一个名为UnmanagedCpp.dll的DLL:
namespace OhYeahNameSpace
{
extern "C" __declspec(dllexport) void Dummy(); //extern "C" to disable name mangling
}
in C#: 在C#中:
class Program
{
[DllImport("UnmanagedCpp.dll")]
public static extern void Dummy();
static void Main(string[] args)
{
Dummy();
}
}
The C# app should be able to find the UnmanagedCpp.dll (ie you can copy it in the bin of the exe) C#应用程序应该能够找到UnmanagedCpp.dll(即你可以将它复制到exe的bin中)
EDIT: 编辑:
This solution has some downsides that should be considered. 该解决方案有一些应该考虑的缺点。 Following the comments, some things I did not state clearly when proposing my "solution". 在评论之后,我在提出“解决方案”时没有明确说明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.