2010-03-04 31 views
1

我有一個簡單的託管C++程序集,我爲C#程序集中的一些靜態方法提供非託管包裝。其中一個方法返回一個字符串,我已經在C++程序集中轉換爲「const char *」類型。我遇到的麻煩是,當我從非託管源加載此dll時,我將錯誤的數據返回到指針中。我能做些什麼呢?我簡化了我的測試用例到這一點:如何從clr程序集中返回char *數組?

管理組件(Test.dll的編譯/ CLR,完整的代碼如下):

extern "C" { 
    __declspec(dllexport) const char* GetValue(const char* s) { 
     return s; 
    } 
} 

非管理控制檯的Win32應用程序:

#include "stdafx.h" 
#include <stdio.h> 
#include <tchar.h> 
#include <windows.h> 

typedef const char* (*GetValueFunc)(const char* s); 

int _tmain(int argc, _TCHAR* argv[]) { 
    wprintf(L"Hello from unmanaged code\n"); 
    HMODULE hDll = LoadLibrary(L"Test.dll"); 
    if (!hDll) 
     return GetLastError(); 

    wprintf(L"library found and loaded\n"); 

    GetValueFunc getValue = (GetValueFunc)GetProcAddress(hDll, "GetValue"); 
    if(!getValue) 
     return GetLastError(); 
    wprintf(L"%s\n", getValue("asdf")); 

    return 0; 
} 

我得到前兩行很好,但出來的第三行是垃圾。如果我讓dll在cpp文件的頂部有「#pragma unmanaged」也沒關係(相同的結果)。

回答

2

當你傳遞一個「const char *」給它時,帶有%s格式說明符的wprintf將把你的第一個參數解釋爲「const wchar_t *」。嘗試在你的GetValue函數中使用wchar_t。

+1

是的,你正在打印一個8位字符串,就好像它是Unicode。這產生中文。使用printf()而不是wprintf()是一個簡單的解決方案。使用%hs而不是%s是另一個便宜的技巧。 –