hbrls
hbrls

Reputation: 2160

How to pass "values" between C# and C++ dll

I have a dll project with C++ like:

_declspec(dllexport) bool __stdcall cppPage1(char* Input, char* Output)
{
    string str1 = Input;
    //blablabla
    strcat(Output, "Result#as#a#string");
}

And in C#, I use this with:

[DllImport("ReportContent.dll")]
extern static bool cppPage1()
public void Page1()
{
    StringBuilder s1 = new StringBuilder("1#3", 10000);
    StringBuilder s2 = new StringBuilder("", 10000);
    cppPage1(s1, s2);
}

As shown above, I "get" some RAM with StringBuilder where C# and C++ both can read/write. C++ read Input from RAM and did calculating logics and write to Output which is also in RAM so that C# can get the result. Let StringBuilder.Length = 10000 to make sure that enough in most situations.

I don't think it is a good practice to consider RAM in C#. What is the right way of communicating between C# and C++?

Upvotes: 1

Views: 1673

Answers (1)

sehe
sehe

Reputation: 393934

You should translate the signature from C to C# using P/Invoke marshaling rules. There are a number of tools to help you with that.

Here is the documentation

Upvotes: 3

Related Questions