Answer the question
In order to leave comments, you need to log in
How to implement string passing in C++ dll, change it and return it to .Net C# project?
There is a project in C #, a dll goes to it on the pluses. It is necessary to pass a string from C # to a function, in which to change it (add / delete a character) and return it back. I collected information on the network on this topic, I did not find a solution. Here I found this toster.ru/q/58640, but this is just a transfer of a string from a lib to C#.
It would be great if the answer to my question is a code example in which, on the C# side, we call a function either with two parameters (strings), in C++ we combine them, return them to C# and display them on the screen.
Answer the question
In order to leave comments, you need to log in
To describe and call functions from regular dlls in c/c++, the Marshal class is used.
You can allocate memory, convert a string, structure to unmanaged memory and vice versa.
The example calls the GetComputerName function, which fills the memory allocated in the program, and then the result is converted to a string and printed to the console.
class Program
{
static void Main(string[] args)
{
// Выделение памяти из неуправляемой области
// Получаем обычный указатель для использования в c/c++ функциях
var pComputerName = Marshal.AllocHGlobal(256);
// Вызываем описанную внешнюю функцию
// Она будет работать непосредственно с памятью по указателю
int size = 256;
GetComputerName(pComputerName, ref size);
// Переводим результат в управляемый вид
var str = Marshal.PtrToStringUni(pComputerName);
Console.WriteLine(str);
// Обязательно освобождаем выделенную память
Marshal.FreeHGlobal(pComputerName);
Console.ReadLine();
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
public static extern void GetComputerName(IntPtr pComputerName, ref int size);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question