Click here to Skip to main content
15,889,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:
C++
class A
{
     public:
     A();
     ~A()
      int C++DllMethod(int*);
 };

CLR Wrapper Class:
C++
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.
Posted
Updated 15-Apr-16 2:50am
v3
Comments
Philippe Mori 15-Apr-16 17:04pm    
The wrapper project should have its own DLL and should be mixed-mode C++.

You should not do conversion on the C# side. Send CLR array to C++/CLI code and convert array to native C++ in that assembly. Otherwise, your application would be polluted by conversion code.

It is much more preferable to split code appropriatly.

1 solution

you must allocate real memory for your array

C#
int[] MyArray = new int[3];


I dont think you need it, but it makes your intention clearer
C#
fixed (int* pointer = MyArray)
{
     A_Wrap Wrapper = new A_Wrap();
     Wrapper.CLRDllMethod(pointer);
    //all stuff with the array
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900