2012-06-20 156 views
2

我嘗試按照此步驟:Calling C# from C++, Reverse P/Invoke, Mixed Mode DLLs and C++/CLI 1.我讓C#DLL的命名TESTLIB:調用C#函數C

namespace TestLib 
{ 
    public class TestClass 
    { 
     public float Add(float a, float b) 
     { 
      return a + b; 
     } 
    } 
} 

2.然後,我創建C++/CLI的Dll名爲WrapperLib和添加對C#TestLib的引用。

// WrapperLib.h 

#pragma once 

using namespace System; 
using namespace TestLib; 

namespace WrapperLib { 

    public class WrapperClass 
    { 
    float Add(float a, float b) 
     { 
     TestClass^ pInstance = gcnew TestClass(); 
     //pInstance 
     // TODO: Add your methods for this class here. 
     return pInstance->Add(a, b); 
     } 
    }; 
} 

C + 3.檢查那朵例子中,我創建C++/CLI控制檯應用程序,並嘗試把這個代碼:

// ConsoleTest.cpp : main project file. 

#include "stdafx.h" 

using namespace System; 
using namespace WrapperLib; 

int main(array<System::String ^> ^args) 
{ 
    Console::WriteLine(L"Hello World"); 
    WrapperClass cl1 = new WrapperClass(); 

    return 0; 
} 

,但我得到了一些錯誤:

error C2065: 'WrapperClass' : undeclared identifier C:\Projects\TestSolution\ConsoleTest\ConsoleTest.cpp 11 1 ConsoleTest 
error C2146: syntax error : missing ';' before identifier 'cl1' C:\Projects\TestSolution\ConsoleTest\ConsoleTest.cpp 11 1 ConsoleTest 
error C2065: 'cl1' : undeclared identifier C:\Projects\TestSolution\ConsoleTest\ConsoleTest.cpp 11 1 ConsoleTest 
error C2061: syntax error : identifier 'WrapperClass' C:\Projects\TestSolution\ConsoleTest\ConsoleTest.cpp 11 1 ConsoleTest 

那麼我知道我錯過了什麼地方,但在哪裏?

+0

如果編譯器告訴你「嗨,出現了一些錯誤,請修復」,你首先看哪裏? :)請告訴我們錯誤是什麼。 –

+0

已修復。我添加了VS輸出。如何從本地C++或C右鍵調用該函數? – Superjet100

回答

1

這不是很好的C++,看起來像Java或C#。

正確的語法C語言創建一個新的對象++/CLI是

WrapperClass cl1; 

WrapperClass^ cl1 = gcnew WrapperClass(); 

C++已經堆棧的語義,你必須告訴編譯器是否要一個本地對象自動放置在功能(第一個選項)的末尾,或者可以使用更長壽命的手柄(第二個選項,使用^gcnew)。

+0

我試着用WrapperClass^cl1 = gcnew WrapperClass();但我得到的錯誤:錯誤錯誤C2065:WrapperClass「:未聲明的標識符 錯誤C2065:CL1':未聲明的標識符\t 錯誤C2061:語法錯誤:標識符 'WrapperClass' – Superjet100

+0

@ Superjet100:您還需要'的#include 「WrapperLib.h」' –

+0

但是在這個測試控制檯應用程序中,我沒有#include「WrapperLib.h」 – Superjet100

2

根據@Ben福格特建議,我相信,你的代碼看起來有點像這樣:

// ConsoleTest.cpp : main project file. 

#include "stdafx.h" 
#include "WrapperLib.h" 

using namespace System; 
using namespace WrapperLib; 

int main(array<System::String ^> ^args) 
{ 
    float result; 
    Console::WriteLine(L"Hello World"); 
    WrapperClass cl1; 

    result = cl1.Add(1, 1); 

    return 0; 
} 

如果不包括你的包裝庫的頭文件,C++編譯器永遠也找不到它的功能並且您將繼續收到您之前顯示的錯誤。

+0

我的WrapperLib項目僅包含帶有代碼和WrapperLib.cpp的WrapperLib.h:#include「stdafx.h」#include「WrapperLib.h」是不是正確? – Superjet100

+0

是的我相信這是正確的,但是你需要將你的WrapperLib頭文件包含到你的主項目(你用來測試它的那個項目)中。正如@Mark Simith上面所說的,在本機C++中,如果您沒有引用另一個項目,則無關緊要,您仍然需要包含頭文件。 – Felipe

+0

此外,也許你可以用你最新的構建錯誤更新你的問題... – Felipe