簡體   English   中英

從C ++使用C#DLL:以字符串為參數的函數問題

[英]using C# DLL from C++: problem with functions with strings as parameters

從以下示例開始: http : //support.microsoft.com/kb/828736我試圖在我的C#DLL中添加一個測試函數,該函數將字符串作為參數。 我的C#DLL代碼如下:

namespace CSharpEmailSender
{
   // Interface declaration.
   public interface ICalculator
   {
       int Add(int Number1, int Number2);
       int StringTest(string test1, string test2);
   };

// Interface implementation.
public class ManagedClass : ICalculator
{
    public int Add(int Number1, int Number2)
    {
        return Number1 + Number2;
    }

    public int StringTest(string test1, string test2)
    {
        if (test1 == "hello")
            return(1);

        if (test2 == "world")
            return(2);

        return(3);
    }
}

然后,我使用regasm注冊此DLL。 我像這樣在我的C ++應用程序中使用它:

using namespace CSharpEmailSender;
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
// Initialize COM.
HRESULT hr = CoInitialize(NULL);

// Create the interface pointer.
ICalculatorPtr pICalc(__uuidof(ManagedClass));

long lResult = 0;
long lResult2 = 0;

pICalc->Add(115, 110, &lResult);
wprintf(L"The result is %d", lResult);

pICalc->StringTest(L"hello", L"world", &lResult2);
wprintf(L"The result is %d", lResult2);

// Uninitialize COM.
CoUninitialize();

return 0;

}

運行此命令后,lResult是正確的(值為225),但是lResult2為零。 知道我在做什么錯嗎?

無需嘗試對此進行編譯,也許互操作程序期望該字符串為BSTR類型。 您可以嘗試以下嗎?

pICalc->StringTest(CComBSTR(L"hello"), CComBSTR(L"world"), &lResult2);

要么

pICalc->StringTest(::SysAllocString(L"hello"), ::SysAllocString(L"world"), &lResult2); 

您在StringTest使用==進行字符串比較,該引用進行引用比較。 (通常)這在純C#中有效,因為所有字符串都經過檢查,但是通過COM傳遞的字符串將等於它們在C#中的等效字符串。 嘗試改用Equals

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM