Click here to Skip to main content
16,020,378 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
I have a C++ project which I want to convert into a C# project. I've converted the DLL calls and codes but when I run the C# version sometimes it runs and sometimes it gives me System.AccessViolationException and jumps out of the program or sometimes it just exits the program without any exception.

What I have tried:

I've converted this function like this:

C++
# define VIXHZ_EXPORT __declspec(dllimport)

VIXHZ_EXPORT long _VixHz_LoginDevice(char *szIp, int nPort, char* szUserName, char* szPassword, base::string& strOutInfo);

base::string strInfo;
long m_login_id = _VixHz_LoginDevice("IP", 80, "Username", "Password", strInfo);


To:
C#
[DllImport(dll)]
public static extern long _VixHz_LoginDevice(string szIp, int nPort, string szUserName, string szPassword, ref string strOutInfo);
        
string output = "";
long m_login_id = _VixHz_LoginDevice("IP", 80, "Username", "Password", ref output);
Posted
Updated 31-May-21 23:05pm
v3

You must take with string between C+ and C#. Here is working code C# interoperation article which concreates on a simple and working interface.

When using C++ strings in C# than you must use these bstrings else you will fail.
 
Share this answer
 
I don't believe that C# has the capacity to automatically understand what a string type is in C++, it's natively unable to convert a C# string into a C++ std::string or otherwise.

Instead of using base::string& as the last parameter consider using char* instead, and then assign the value within the method. Alternatively you can use a StringBuilder so that the C++ method can write to the value.

For example:
C#
// C++
VIXHZ_EXPORT long _VixHz_LoginDevice(char *szIp, int nPort, char* szUserName, char* szPassword, char* strOutInfo, int strOutInfoLength);

// C#
[DllImport(dll)]
public static extern long _VixHz_LoginDevice(string szIp, int nPort, string szUserName, string szPassword, StringBuilder strOutInfo, int strOutInfoLength);

// Call
StringBuilder strOut = new StringBuilder(32);
_VixHz_LoginDevice("1.2.3.4", 1234, "username", "password", strOutInfo, strOutInfo.Capacity);

You can omit the length parameter if you know exactly what the maximum length is expecting to be and the C++ isn't going to exceed it. An example with the StringBuilder can be found here:

Default Marshaling for Strings | Microsoft Docs[^]
 
Share this answer
 

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