dll - 如何使用 Marshal 类编译 C++ DLL

标签 dll c++-cli

我昨天刚开始使用 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/

相关文章:

visual-studio - 为什么 DLL 函数调用没有编译为相关的 CALL 指令

.net - 如何从 ArrayList 转换为 cli::array?

.net - 如何为 C++/cli 项目指定默认命名空间?

c++-cli - 从 C++/CLI 指针转换为 native C++ 指针

c# - 将数组参数从 C# 传递到 C++/CLI 方法

deployment - 一个大的可执行文件还是许多小的DLL?

c# - 条件符号不起作用

c++ - 使用 C++/CLI 包装 native C++ 模板化类

c++ - DLL 锁定 - Visual Studio 2010 C++

c++ - 拆解 C++ DLL 函数名称