开发者

AccessViolationException when trying to call c++ external function with 'new char[...]' inside it

I catched a strange issue when i was trying to call unmanaged c++ function from c# code.

the c++ function looks like this:

extern "C"{
__declspec(dllexport) int Test(char * pixels, int length, int heigh开发者_如何学Got){
    int width = length / height;
    // char * test = new char[length];
    return width;
  }
}

And from C# I'm trying to call it using next constructions:

[DllImport("Test.exe", EntryPoint = "Test")]
public static extern int Test(byte[] pixels, int length, int height);
...
var bytes = new byte[] { 1, 1, 1, 1, 1 };
var height = 1;
var result = Test(bytes, bytes.Length, height);

This code works well, but... If I try to uncomment c++ line with 'new', i'm getting the System.AccessViolationException.

Can anybody explain what happening there and why?

UPDATED

Thanks to David Heffernan, and now my code looks like this:

[DllImport("Test.exe", EntryPoint = "Test", 
    CallingConvention = CallingConvention.Cdecl)]
public static extern int Test(byte[] pixels, int length, int height);

Unfortunately it changes nothing

RESOLVED

Don't use *.exe as module. Everything works well after compilation module as dynamic library.

It's caused by fundamental differences between DLLs and executable file linking. For more infomation see MSDN LoadLibrary page and MSDN About DLLs page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜