Converting from c# string to c++ string

I’m using a Dll created from a C++ file. When I either put the .dll and .lib files in my Unity-project folder or when I use the function that I need, Unity crashes and I can’t open the project untile I remove the .dll or delete the function from the c# script.

This function works well on C++, both in Visual Studio and in Dev-C++

PS: Assets/alzBraccioCorretto.json is the file that I need to read

I’ve tried the same procedure for more simple dlls (just functions with int or double variables) and it worked fine, so I don’t know what I’m missing with this one, probably UNICODE

In the Unity script I wrote

[DllImport("QuartaLibreria.dll", CharSet = CharSet.Unicode)]

static extern string LeggiFile(string nomeFile);

Text testo;

unsafe void Start()
{
testo = GetComponent<Text>();

temp = LeggiFile("Assets/alzBraccioCorretto.json");
testo.text = temp;
}

In the header of the library I have

#define QUARTALIBRERIA_API __declspec(dllexport)

//all the other headers and #include

string leggiFile(char* nomeFile);

extern "C" {
QUARTALIBRERIA_API wstring LeggiFile(wstring nomeFile);}

In the cpp of the library I have

string leggiFile(string nomeFile) {

ifstream _stream(nomeFile.c_str());
string temp;
_stream >> temp >> temp;
_stream.close();
return temp;
}

QUARTALIBRERIA_API wstring LeggiFile(wstring nomeFile){
std::string str(nomeFile.begin(), nomeFile.end());
string daRit = leggiFile(str);
std::wstring WdaRit(daRit.length(), L' '); // Make room for characters

std::copy(daRit.begin(), daRit.end(), WdaRit.begin());

return WdaRit;
}

You can not return a string from a native code method. Inside .NET managed land memory has to be managed memory. Have a look at this SO question. If you want to return string data to C# you should reverse the ownership. So you have to allocate the buffer memory on the managed side and pass a pointer to the native method which can fill the the buffer.

Though your code looks a bit strange. Why would you pass a file name to a native code plugin to read the content and then just return that content back to native code?