0

i have a problem with a dllimport, first the C++ code:

   extern "C" {
   __declspec(dllexport) int wmain(char* configr, char* path)
   {
     ILoggerPtr logger;

   try
   {        
     _bstr_t config(configr);
     _bstr_t srcFile(path); 
   }

My C# Code:

    [DllImport(@"Test.dll")]
    static extern int wmain(string config, string path);

The call for to C++:

    string path = "c:\\bmp\\" + im.ID_MOVIMENTO + "_gray.bmp";
    temp.Save(path, System.Drawing.Imaging.ImageFormat.Bmp);
    int k = wmain("Brasil", path);

Oks, the problem, in the first conversion in C++ char* to _bstr_t have the error: An unhandled exception of type 'System.AccessViolationException' occurred in CarregadorFotos.exe

Someone have any idea to manage this error?

JonesVG
  • 21
  • 1
  • 7
  • 1
    Yet another case of a missing CallingConvention.Cdecl – Hans Passant Jan 29 '14 at 17:53
  • possible duplicate of [Proper calling convention of unmanaged DLL function](http://stackoverflow.com/questions/18208084/proper-calling-convention-of-unmanaged-dll-function) – Hans Passant Jan 29 '14 at 18:20
  • Sorry friend, but don't work, now throw the excption in the start of function. – JonesVG Jan 29 '14 at 18:46
  • An unhandled exception of type 'System.AccessViolationException' occurred in CarregadorFotos.exe Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. The thread 'Win32 Thread' (0x738) has exited with code 0 (0x0). – JonesVG Jan 29 '14 at 18:53

1 Answers1

0

Your C# signature should be:

  [DllImport(@"Test.dll")]
    static extern int wmain([MarshalAs(UnmanagedType.LPStr)]string config, 
[MarshalAs(UnmanagedType.LPStr)]string path);

or

  [DllImport(@"Test.dll")]
    static extern int wmain(IntPtr config,  IntPtr path);

and as Hans Passant said, use CallingConvention.Cdecl or you might get a "Unbalanced stack" exception

Idov
  • 5,006
  • 17
  • 69
  • 106
  • 1
    [DllImport(@"UrmTest.dll", CallingConvention = CallingConvention.Cdecl)] static extern int wmain([MarshalAs(UnmanagedType.LPStr)]string config, [MarshalAs(UnmanagedType.LPStr)]string path); don't work, and the other don't work to. The same error. – JonesVG Jan 29 '14 at 19:06
  • Some time gives me a error in xstring in the moemnt of conversion char to _bstr_t – JonesVG Jan 29 '14 at 19:12
  • so maybe it's not a marshalling error. You may have a bug in your C++ code. – Idov Jan 29 '14 at 19:15
  • oks, thanks, i have this conevertion _bstr_t config(configr); configr its a char*. Nothing more before this convertion. – JonesVG Jan 29 '14 at 19:18