关于互操作性的几个问题 - 在C#中使用的C ++导出函数 [英] Few questions on interopability - C++ exported functions to use in C#

查看:105
本文介绍了关于互操作性的几个问题 - 在C#中使用的C ++导出函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我有一个用C ++编写的代码,我需要在C#应用程序中使用。

下面是语法的我需要在C#应用程序中使用的两种方法:

Hi All,

I have a code written in C++ which i need to consume in C# Application.
Below are the syntax's of the two methods which i need to use in my C# application:

long __declspec (dllimport) MyMethod1(const wchar_t* inputFileName, const wchar_t* outputFileName)

__declspec (dllimport) int __stdcall MyMethod2(void ** pMyVoidPtr, MY_CUSTOM_STRUCT* pMyCustomStruct);



我可以在我的C ++应用程序中使用它们,如下所示:


I could use them in my C++ Application as below:

MyMethod1(_T("C:\\InputFile.txt"), _T("C:\\OutputFile.txt"));

MY_CUSTOM_STRUCT myCustomStruct;

void* pVoidPtr = NULL;

MyMethod2(&pVoidPtr, &myCustomStruct);



在C ++应用程序中,我可以获得所需的结果。但是在C#应用程序中,指针pVoidPtr总是返回NULL。



我尝试使用ref,输出IntPtr作为参数,但一切都失败了。



任何人都可以在C#应用程序中为我提供相同的语法(对于这两种方法)?



谢谢和问候,
Kishor Reddy



我尝试过:




In C++ Application, i could get the desired results. But in C# Application, the Pointer pVoidPtr always returns NULL.

I have tried using ref, out IntPtr as parameters but everything failed.

Could anyone provide me the syntax for the same in C# Application (For both the methods)?

Thanks and Regards,
Kishor Reddy

What I have tried:

[DllImport("Exported Dll Path")]
long static extern MyMethod1(string strInputName, string strOutputName);

[DllImport("Exported Dll Path")]
int static extern MyMethod2(out IntPtr pVoidPtr, MY_CUSTOM_STRUCT myCustomStruct);

[DllImport("Exported Dll Path")]
int static extern MyMethod2(out IntPtr pVoidPtr, IntPtr myCustomStruct);

推荐答案

首先Garth是对的,你必须导出从外面访问它们的功能。



不应该从一个运行时(C ++)导入内存或分配objext到另一个(C#)。你不喜欢陷阱。从C#中提供足够大的缓冲区,可能在询问C ++之后使用显式函数而不是分配并执行调用。



读取我的文章以一些简单的方式来处理这个问题。最后还是一个处理更复杂场景的链接。
At first Garth is right you must export the functions to access them from outside.

And you shouldnt import memory or allocated objext from one runtime (C++) into another (C#). You wont like the pitfalls. Provide a big enough buffer from C#, maybe after asking C++ with an explicit function and than allocate and execute the call.

Read my article for some simple way to deal that issue. At the end is also a link where a more complexer scenario is handled.


这篇关于关于互操作性的几个问题 - 在C#中使用的C ++导出函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆