从 C++ DLL 函数返回 wchar_t* 到 C# 不起作用

问题描述 投票:0回答:1

我正在维护一些旧的 C++ 代码,并且我一整天都在努力找出为什么从 C# 调用该代码时不起作用。第一个功能工作正常,第二个功能失败。

C++ DLL 代码:

static const wchar_t *TEST = const_cast<wchar_t*> (L"TEST");

EXPFUNC const unsigned int __stdcall testFunc1(const wchar_t *str) {

    // there is logic here that does a lookup using *str and returns an id

    return 123;
}

EXPFUNC const wchar_t* __stdcall testFunc2(const unsigned int id) {

    // there is logic here that does a lookup using id and returns the pointer

    return TEST;
}

C#代码:

[DllImport("Test.dll", CallingConvention = CallingConvention.Cdecl)]
internal static extern uint testFunc1([MarshalAs(UnmanagedType.BStr)] string symbol);        

[DllImport("Test.dll", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.BStr)]
internal static extern string testFunc2(uint id);


testFunc1("some string");  // works

testFunc1(123);  // exited with code 3221226356
c# c++ dll
1个回答
0
投票

您的 C# 代码将返回值封送为

UnmanagedType.BStr
,但您的 C++ 代码未返回有效的
BSTR

© www.soinside.com 2019 - 2024. All rights reserved.