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
Release: 2025-01-03 19:35:41
Original
329 people have browsed it

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;
    }
}
Copy after login

In C#, the function is called using interop:

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

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
}
Copy after login

And in C#:

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

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
}
Copy after login

In C#:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template