2
我試圖學習如何在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;
}
我認爲,沒有任何評論
您正在使用基本的語言語法。但是,最重要的是通過嘗試在DllMain()中運行託管代碼,挖掘出自己永遠無法擺脫的深淵。這是被禁止的,這將觸發臭名昭着的裝載機鎖定。找一個體面的教程或書籍來避免犯這些錯誤。 –
感謝您的回答。但我可以調用外部託管的dll從我的非託管DllMain調用它嗎? – user2598575
Im found info:http://msdn.microsoft.com/ru-ru/library/ms173266.aspx – user2598575