Click here to Skip to main content
15,885,039 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a VS2013 solution with 2 projects. One is a c++/cli dll. The other is a c# console app. The dll contains a class whose ctor takes a 'const WCHAR *' parameter. In the c# app I tried to create an instance of the class. I used a string literal for the ctor parameter. The build error is:

The best overloaded method match for 'MyLib.MyClass.Myclass(char*)' has some invalid arguments

I have 2 questions.

1. Why does VS2013 think the parameter is 'char*' instead of 'WCHAR*'?

2. How can I pass a string from c# to c++?

The purpose of this work is to see if using a c++/cli dll is easier than just using dllimport/pinvoke.
Posted
Comments
Philippe Mori 10-Sep-15 23:41pm    
Make your C++/CLI code compatible with other .NET languages.

char in C# mean a 16 bit unicode character.

1 solution

If this is C++/CLI, you can write managed CLI code which is, basically, the same as C#. You just need to use managed "ref" classes. Instead of WCHAR*, use System::String^. Such types (if you use public access modifiers for them and some of their members) will be exposed to the referencing assembly in exact same ways as in C# or VB.NET.

You are trying to use explicit P/Invoke for unmanaged classes.
  1. VS2013 does not "think" anything; it's not clear how you face such thing; however, default marshaling can marshal char* as System.String. In general case, you need to use MarshalAs attribute: https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshalasattribute%28v=vs.110%29.aspx[^].
  2. I explained the idea above. But you don't really need to pass System::String to C++. Pass it to C++/CLI, using a managed class. If you have C++ unmanaged code you just have to continue to use, you can wrap in in your "ref" managed types. In other word it's much more maintainable way to implement managed to unmanaged binding inside C++ project, not inside C# project, without explicit use of P/Invoke.

    Please see:
    https://msdn.microsoft.com/en-us/library/ms235282.aspx[^],
    https://msdn.microsoft.com/en-us/library/2x8kf7zx.aspx[^],
    https://msdn.microsoft.com/en-us/library/eyzhw3s8.aspx[^].


See also my past answers:
How to invoke C++ DLL in ASP.NET?[^],
Dealing with windows form application[^],
How do I catch native c++ exception in managed c++ class?[^].

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900