我试图学习如何在CLI / C ++中编写混合代码。
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;
}
}
}
虽然对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命名空间? 我做错了什么?
感谢。
[ADDED]
我在微软网站上找到了一些代码。可能对某人有用:
// 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;
}
我认为,没有评论
答案 0 :(得分:1)
你用过
#pragma unmanaged
因此,您无法在那里使用任何托管代码。