通过CLR包装器实用程序从C#应用程序调用非托管方法 [英] Calling unmanaged methods from C# application via CLR wrapper utility

查看:72
本文介绍了通过CLR包装器实用程序从C#应用程序调用非托管方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在C#应用程序中使用我的C ++ DLL。我在CLR中创建了一个包装器项目并与C#app链接。

我在访问我的CLR包装器方法中的c#应用程序中创建的内存时遇到随机崩溃,有时在我的C ++ dll项目中。

我相信我的dll项目是一个万无一失的项目。

我用消息测试我的代码以找到错误的代码。但我找不到原因。

C ++类:

  class  A 
{
public
A();
~A()
int C ++ DllMethod( int *);
};



CLR Wrapper Class:

  class  A_Wrap 
{
A_Wrap();
~A_Wrap();
int CLRDllMethod( int *);
};



C#Applicatio n:

 int [] MyArray = {10,10,10}; 
int * IntVal = null;
fixed(int * ii = MyArray)
IntVal = ii;
A_Wrap Wrapper = new A_Wrap();
Wrapper.CLRDllMethod(IntVal);





我的尝试:



未定义值显示在CLR项目中崩溃时指针变量(int *)的堆栈栏显示。

我想知道问题可能在于C#app中的内存分配并将其传递给CLR包装器项目。

我在CLR项目中尝试了pin_ptr概念并且它也没有用我。



避免崩溃所需的建议。

解决方案

你必须为阵列分配实内存



  int  [] MyArray =  new   int  [ 3 ]; 





我认为你不需要它,但它会使你的意图更清楚

  fixed (int * pointer = MyArray)
{
A_Wrap Wrapper = new A_Wrap();
Wrapper.CLRDllMethod(指针);
// 数组的所有内容
}


I need to use my C++ dll in C# application. I created a wrapper project in CLR and linked with C# app.
I am getting random crashes while accessing the memory created in c# application in my CLR wrapper methods and sometimes in my C++ dll project.
I am sure my dll project is a foolproof one.
I tested my code with messages to find the erroneous code.but i couldn't find out the reason.
C++ Class:

class A
{
     public:
     A();
     ~A()
      int C++DllMethod(int*);
 };


CLR Wrapper Class:

class A_Wrap
{
    A_Wrap();
    ~A_Wrap();
    int CLRDllMethod(int*);
};


C# Application:

int[] MyArray = { 10, 10, 10 };
     int* IntVal = null;
     fixed (int* ii = MyArray)
         IntVal = ii;
     A_Wrap Wrapper = new A_Wrap();
     Wrapper.CLRDllMethod(IntVal);



What I have tried:

"undefined value" is shown at the stack bar display for the pointer variable(int*) while crashing in CLR project.
I wonder the problem could be with the memory allocation in C# app and passing it to CLR wrapper project.
I tried pin_ptr concept in CLR project and it also didnt work for me.

Suggestions needed to avoid the crash.

解决方案

you must allocate real memory for your array

int[] MyArray = new int[3];



I dont think you need it, but it makes your intention clearer

fixed (int* pointer = MyArray)
{
     A_Wrap Wrapper = new A_Wrap();
     Wrapper.CLRDllMethod(pointer);
    //all stuff with the array
}


这篇关于通过CLR包装器实用程序从C#应用程序调用非托管方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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