I have a C++ class which has a header(matrixheader.h) such that :
#pragma once
class M
{
public:
M(int m,int n);
void MSet(int m,int n,double d);
double MGet(int m,int n);
~M();
private:
double** mat;
};
Class is defined as follows in (matrixbody.cpp):It is built in Win32 Platform.
#pragma once
#include "matrixhead.h"
M::M(int m,int n)
{
mat = new double*[m];
for (int i = 0; i < m; i++)
{
mat[i] = new double[n];
}
}
void M::MSet(int m,int n,double d)
{
mat[m][n] = d;
}
double M::MGet(int m,int n)
{
double d = mat[m][n];
return d;
}
M::~M()
{
delete[] mat;
}
I have made a wrapper for the Class like so(matrixwrapper.cpp):The wrapper is also built in Win32 platform.
#include "matrixhead.h"
#include "matrixbody.cpp"
extern "C" __declspec(dllexport) void* Make(int m,int n)
{
M o(m,n);
return &o;
}
extern "C" __declspec(dllexport) void setData(void* mp,int m,int n,double d)
{
M* ap = (M*)mp;
M a = *ap;
a.MSet(m,n,d);
}
extern "C" __declspec(dllexport) double getData(void* mp,int m,int n)
{
M* bp = (M*)mp;
M b = *bp;
double d = b.MGet(m,n);
return d;
}
I import the class to C# and try to call the C++ dl methods from C#:
using System;
using System.Runtime.InteropServices;
namespace wrappertest
{
class Program
{
[DllImport("matrixwrapper.dll")]
unsafe public static extern void* Make(int m,int n);
[DllImport("matrixwrapper.dll")]
unsafe public static extern void setData(void* mp,int m, int n,double d);
[DllImport("matrixwrapper.dll")]
unsafe public static extern double getData(void* mp,int m, int n);
static unsafe void Main(string[] args)
{
void* p = Make(10, 10);
setData(p,10,1,10);
Console.WriteLine(getData(p,10,1));
}
}
}
But when i try to run the C++ dll methods from C# i get the following error
1//Attempted to read or write protected memory.This is often an indication that other memory is corrupt when running C# code in x64.
2//An attempt was made to load a program with incorrect format when runnning in x86 Active/x86 or in AnyCPU platform.
Questions:
1//What is wrong in the above code ?
2//Considering that my final objective is to make a 2d dynamic array in C++ and read/write data in the array such as the one double**mat in the matrixheader.h file above from C#?is there any other way to implement it ?