将字符串从DLL传递到C# 我有一个C语言应用程序,它使用CLI DLL访问非托管C++库中的函数。我的问题是,我不能从C++库中获取文本,以便正确地传递给C语言应用程序。到目前为止,我的守则如下:

将字符串从DLL传递到C# 我有一个C语言应用程序,它使用CLI DLL访问非托管C++库中的函数。我的问题是,我不能从C++库中获取文本,以便正确地传递给C语言应用程序。到目前为止,我的守则如下:,c#,c++,dll,c++-cli,parameter-passing,C#,C++,Dll,C++ Cli,Parameter Passing,C# CLI C++ //在标题中。 类应用程序{ void GetNameLength(int索引、int和size); 常量字符*GetName(int索引); }; //在“.cpp”中。 void应用程序::GetNameLength(int索引、int和size){ 如果(索引>=0&&index=0&&index if( gp_app == nullptr) return false; 如果是这样,您可以导出托管类并使用字符串作为方法的参数 检查此:在我看来,你的C++部分

C#

CLI

C++

//在标题中。
类应用程序{
void GetNameLength(int索引、int和size);
常量字符*GetName(int索引);
};
//在“.cpp”中。
void应用程序::GetNameLength(int索引、int和size){
如果(索引>=0&&index=0&&index
我能够调试到DLL中,并且我看到它确实正确地复制了名称,即使我只是使用
name=const_cast(n)
(以及使用字符串而不是StringBuilder),但由于某种原因,该值没有从DLL返回到C

<>我读到一个可能的原因是因为C++使用ASCII字符,而C使用16位字符,并且它的修正是包含<代码>字符集=字符集.ANSI ,这样当返回C时它就被正确地编组了,但是这显然没有帮助。 谁能告诉我我做错了什么


解决方案

使用
public ref类
而不是命名空间,并使用
void Foo([Out]String^%name)声明函数
确保
使用命名空间System::Runtime::InteropServices被包含。

这说明你实际上有一个托管C++ dll。< /p>
if( gp_app == nullptr)
    return false;
如果是这样,您可以导出托管类并使用字符串作为方法的参数


检查此:

在我看来,你的C++部分中头和实现的代码不匹配,代码< > GETNEX/COD>(如果你使用一个ARG,另两个),如果你使用C++ + CLI,为什么要麻烦DLL出口?使用
ref类
,你可以像使用C#.@500 InternalServerError一样使用它。啊,对不起,在跨代码复制时,这是一个输入错误。@crashmstr,因为我以前没有使用过
ref类
,而且我用这个方法实现了相当多的代码。CAN <代码> REF类< /C>使用指向非托管C++类的指针吗?我尝试使用<代码>字符串和<代码> StringBuilder <代码>作为我的包装器中的参数,但是这意味着我不能将它分配给<代码>这意味着它不能被导出用于我的C#代码。@Edward使用ref类并从那里调用这些函数。然后使用字符串构造函数来创建托管字符串。我只是尝试更改为ref类,并使用
name=%String(n)
对其进行编译,然后调试到其中,
name
被正确更新为正确的值,但该值在离开函数后仍然没有被传递回我的C#代码中。如果我尝试这样做,您应该将name参数声明为out String ^name,它说的是
“out”:未声明的标识符。与
ref
相同(但将类声明为
public ref class
)也可以。
// In the header.
#define DllExport __declspec( dllexport)

extern "C" {
    DllExport bool __cdecl GetNameLength( int index, int& size);
    DllExport bool __cdecl GetName( char* name, int size, int index);
};


// In the '.cpp'.
bool __cdecl GetNameLength( int index, int& size) {
    if( gp_app == nullptr)
        return false;

    gp_app->GetNameLength( index, size);

    return true;
}

bool __cdecl GetName( char* name, int index, int size) {
    if( gp_app == nullptr)
        return false;

    const char* n = "";
    n = gp_app->GetName( index);

    name = new char[size];
    strcpy( name, n);

    return true;
}
// In the header.
class App {
    void GetNameLength( int index, int& size);
    const char* GetName( int index);
};

// In the '.cpp'.
void App::GetNameLength( int index, int& size) {
    if( index >= 0 && index < gs_namesCount)
        size = strlen( gs_names[index]);
}

const char* App::GetName( int index) {
    if( index >= 0 && index < gs_namesCount)
        return gs_names[index];

    return nullptr;
}
if( gp_app == nullptr)
    return false;