Home >Backend Development >C++ >How to Seamlessly Pass Strings Between C# and C DLLs?

How to Seamlessly Pass Strings Between C# and C DLLs?

Susan Sarandon
Susan SarandonOriginal
2025-01-03 19:35:41312browse

How to Seamlessly Pass Strings Between C# and C   DLLs?

Passing Strings from C# to C DLL and Back

When attempting to pass strings between C# and C , developers often encounter difficulties. In this article, we delve into this issue and provide a concise solution.

The Problem

Consider the following code, where C defines a function to concatenate strings:

extern "C" {
    string concat(string a, string b){
        return a + b;
    }
}

In C#, the function is called using interop:

[DllImport("*****.dll", CallingConvention = CallingConvention.Cdecl)]
    static extern string concat(string a, string b);

However, this approach results in a System.AccessViolationException.

The Solution

The problem lies in the incompatibility of C std::string with the interoperability boundary. To resolve this issue, interop-friendly types must be used at the boundary, such as null-terminated arrays of characters.

Passing Strings from C# to C

For strings passed from C# to C , the C function can be modified:

void foo(const char *str)
{
    // do something with str
}

And in C#:

[DllImport("...", CallingConvention = CallingConvention.Cdecl)
static extern void foo(string str);

Passing Strings from C to C#

For strings passed from C to C#, the C function becomes:

void foo(char *str, int len)
{
    // write no more than len characters into str
}

In C#:

[DllImport("...", CallingConvention = CallingConvention.Cdecl)
static extern void foo(StringBuilder str, int len);

By adhering to these guidelines, developers can pass strings seamlessly between C# and C DLLs.

The above is the detailed content of How to Seamlessly Pass Strings Between C# and C DLLs?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn