Unable to Import C++ Function in C# using Digital Mars compiler but not using VS 2012

The following simple C++ program is compiled using Digital Mars (v 8.57) and also using Visual Studio 2012 Empty C++ project type (build target 86). When I try to import the functions in a C# program, the application crashes reading the Digital Mars version but works fine using the VS version. When I run in debug mode, the function returns "Function Evaluation Was Aborted" and attempts multiple times to evaluate then stops. I'm running on Windows 7 64 bit.

C++ program:
#include <stdio.h>
#include <windows.h>

extern "C"
{
_declspec(dllexport) LPSTR ReturnString()
{

return "HI THERE";

}
_declspec(dllexport) int ReturnInt()
{

int myvalue = 12;
return myvalue;

}
_declspec(dllexport) void ReturnNothing()
{

printf("Hello World");

}
}

int main()
{

return 0;
}


C# Program:

using System;
using System.Runtime.InteropServices;
using System.Threading;

namespace TestCSharp
{
class Program
{
public const string strPath = "C:\\Code Blocks Projects\\Test\\bin\\Debug\\Test.dll";
//public const string strPath = "C:\\Visual Studio 2012\\Projects\\TestCPPEmpty\\Debug\\TestCPPEmpty.dll";

[DllImport("User32.dll")]
public static extern int MessageBox(int h, string m, string c, int type);

[DllImport(strPath, EntryPoint = "ReturnInt")]
public static extern int ReturnInt();

[DllImport(strPath, EntryPoint = "ReturnString")]
public static extern string ReturnString();

[DllImport(strPath, EntryPoint = "ReturnNothing")]
public static extern void ReturnNothing();

public static void Main()
{
//call winapi function
MessageBox(0, "API Message Box", "API Demo", 0);

int myvalue = ReturnInt();
Console.WriteLine(myvalue);

ReturnNothing();

string mystring = ReturnString();
Console.WriteLine(mystring);

}
}
}
The problem is the C++ decoration / name mangling:

https://en.wikipedia.org/wiki/Name_mangling

It is probably different for the Digital Mars Compiler.
Does it crash for any function or just certain ones? Are you importing this into a 64-bit project?

Then there is this: http://www.digitalmars.com/ctg/ctgP05.html

Digital Mars Website wrote:
The layout of the struct_iob in stdio. h is different for Digital Mars C++. Therefore, you cannot link buffered I/ O functions compiled with Digital Mars' stdio. h with buffered I/ O functions compiled with a different stdio. h. To avoid problems, compile all modules in a program with the same version of stdio. h.

Which might have something to do with it :\ .

MIDL isn't really that hard and it solves for pesky crap like that. You should at least give it a look before reinventing the wheel.
Last edited on
Topic archived. No new replies allowed.