C++ cli从非托管代码调用托管代码

问题描述:

我试图学习如何在CLI/C++中编写混合代码。C++ cli从非托管代码调用托管代码

clrHookLib.h

#pragma once 
#pragma managed 
using namespace System; 
namespace clrHookLib { 

    ref class MyClass 
    { 
     // TODO: Add your methods for this class here. 
     public: 
     static int sum(int a, int b); 
    }; 

} 

clrHookLib.cpp

#include "stdafx.h" 
#include "clrHookLib.h" 

int clrHookLib::MyClass::sum(int a, int b) 
{ 
    return a + b; 
} 

的main.cpp

#include "clrHookLib.h" 
#include "Stdafx.h" 

#pragma unmanaged 

BOOL WINAPI DllMain(
    _In_ HINSTANCE hInstance, 
    _In_ DWORD  Reason, 
    _In_ LPVOID  Reserved) 
{ 
    switch (Reason) 
    { 
     case DLL_PROCESS_ATTACH: 
     { 
      int b = clrHookLib::MyClass::sum(1, 2); 
      std::string str = std::to_string(b); 
      MessageBoxA(0, str.c_str, "result from managed code!!", MB_OK); 
      break; 
     } 
    } 
} 

虽然compillin g Visual Studio向我展示了一个错误:

Error 2 error C2653: 'clrHookLib' : is not a class or namespace name C:\Users\*\Documents\Visual Studio 2013\Projects\clrHookLib\clrHookLib\Main.cpp 15 1 clrHookLib 
Error 3 error C3861: 'sum': identifier not found C:\Users\*\Documents\Visual Studio 2013\Projects\clrHookLib\clrHookLib\Main.cpp 15 1 clrHookLib 
Error 4 error C3867: 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>::c_str': function call missing argument list; use '&std::basic_string<char,std::char_traits<char>,std::allocator<char>>::c_str' to create a pointer to member C:\Users\*\Documents\Visual Studio 2013\Projects\clrHookLib\clrHookLib\Main.cpp 17 1 clrHookLib 

问题是为什么compiller无法找到clrHookLib命名空间? 什么即时做错了?

谢谢。

[加]

我发现在微软网站的一些代码。可能这将是有用的人:

// initializing_mixed_assemblies.cpp 
// compile with: /clr /LD 
#pragma once 
#include <stdio.h> 
#include <windows.h> 
struct __declspec(dllexport) A { 
    A() { 
     System::Console::WriteLine("Module ctor initializing based on global instance of class.\n"); 
    } 

    void Test() { 
     printf_s("Test called so linker does not throw away unused object.\n"); 
    } 
}; 

#pragma unmanaged 
// Global instance of object 
A obj; 

extern "C" 
BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { 
    // Remove all managed code from here and put it in constructor of A. 
    return true; 
} 

我认为,没有任何评论

+1

您正在使用基本的语言语法。但是,最重要的是通过尝试在DllMain()中运行托管代码,挖掘出自己永远无法摆脱的深渊。这是被禁止的,这将触发臭名昭着的装载机锁定。找一个体面的教程或书籍来避免犯这些错误。 –

+0

感谢您的回答。但我可以调用外部托管的dll从我的非托管DllMain调用它吗? – user2598575

+0

Im found info:http://msdn.microsoft.com/ru-ru/library/ms173266.aspx – user2598575

您使用 #pragma unmanaged

所以,你不能使用任何托管代码出现。