我昨天刚开始使用 C++,但我被困在一个我怀疑是微不足道的问题上。主 DLL 类正在生成错误 C2653:“Marshal”:不是类或命名空间名称。
我很确定我已经从 MSDN 页面上几乎逐字复制了使用此类的语法。这是代码:
// VideoInfoAssembly.cpp
// compile with: /clr
using namespace std;
using namespace System;
using namespace System::Runtime::InteropServices;
#include "stdafx.h"
#include "VideoInfoAssembly.h"
#pragma managed
namespace VideoInfoAssembly
{
short VideoInfo::GetWidth(System::String^ managedString)
{
// Marshal the managed string to unmanaged memory.
char* stringPointer = (char*) Marshal::StringToHGlobalAnsi(managedString).ToPointer();
// Always free the unmanaged string.
Marshal::FreeHGlobal(IntPtr(stringPointer));
return 9001;
}
}
在较高级别上,我有一个 C# 应用程序需要读取视频文件的视频属性,而 Microsoft Media Foundation 需要 C++。我已经成功构建了 DLL,并作为测试返回了 9000 以上。现在,我尝试将托管字符串传递给 DLL(这将是视频文件名);然而,我已经奋斗了一个多小时才让 Marshal 类发挥作用。如前所述,我一直在使用 MSDN页面没有成功。我缺少什么?
最佳答案
这是由预编译头引起的问题。编译器将跳过所有内容,直到找到预编译头文件的#include。您犯的错误是没有将 #include "stdafx.h"
放在文件顶部。所以像这样修复它:
#include "stdafx.h" // Has to be first
#include "VideoInfoAssembly.h"
using namespace std;
using namespace System;
using namespace System::Runtime::InteropServices;
// etc..
关于dll - 如何使用 Marshal 类编译 C++ DLL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12249652/