0

I am using Visual Studio 2020 (v143). To test exporting a DLL file from a C++ project and importing it in a C# project, I just made a simple DLL file from this code in C++:

extern "C"
{
    __declspec (dllexport)
    int Function() { return 0;} 
}

Compiled in Debug mode for x64 platform, the output DLL file is created.

In a C# project when I try to Add -> Project References... the DLL file, I got this error in a poped up window.

The reference is invalid or unsupported

C++ compiler uses ISO C++14 Standard and the Target Framework of C# was .NET 6

I remember years back when I had used VS 2015 with C++11 and .NET 4.0, I did not face such an error.

What should I do to address this issue?

Thanks.

  • 1
    Your memory is wrong. [Using vs DllImport?](https://stackoverflow.com/questions/5273303/using-vs-dllimport) – shingo Jun 17 '23 at 07:55
  • 1
    C++ and C++/CLI are not the same thing, which is probably where your confuson stems from. You need `DllImport` to access that function – Charlieface Jun 18 '23 at 00:48

1 Answers1

1

You need to use DllImport. And from your another thread Avoid passing containers in dll. Use extern "C" and char* to pass string.

C++

extern "C"
{
    __declspec (dllexport)  int Function();
       
    __declspec (dllexport)const char* __stdcall Function2(int Num);
}
const char* __stdcall Function2(int Num)
{
    std::string str = std::to_string(Num);
    char* result = new char[str.length() + 1];
    strcpy_s(result,str.length()+1, str.c_str());
    return result;
}

C#

   [DllImport("XXX.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "Function")]
    static extern int Function();
    [DllImport("XXX.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "Function2")]
    static extern IntPtr Function2(int Num);
    static void Main(string[] args)

    {  
        IntPtr result = Function2(100);
        string str = Marshal.PtrToStringAnsi(result);

        Console.WriteLine(str);
        Marshal.FreeCoTaskMem(result);

    }
Minxin Yu - MSFT
  • 2,234
  • 1
  • 3
  • 14
  • Hi. Thanks for your reply to my queries. You are right and I got the idea of not passing C++ containers to C# and I managed to stick to native types. But out of curiosity, would it be impossible to, say for instance, pass a std::vector to C# and try to construct a List in there without ising CLI or it would be TOO difficult to do? – Iman Abdollahzadeh Jun 20 '23 at 10:36
  • It is possible but complicated. For your reference: [Passing a vector/array from unmanaged C++ to C#](https://stackoverflow.com/questions/31417688/passing-a-vector-array-from-unmanaged-c-to-c-sharp) – Minxin Yu - MSFT Jun 21 '23 at 06:43