如何在 C 应用程序中使用 C# DLL
How to use a C# DLL in a C application?
我有 C# DLL,我在 COM 互操作的帮助下C++使用该 DLL,方法是在我的.cpp
文件中导入相应的.tlb
文件#import "com.MyIntrop.tlb"
并且它工作得非常好。
现在我想在我的 C 代码中使用相同的 DLL,但由于我不能在 C 中使用#import
如何使用我在 C 中注册为 COM 程序集的相同 DLL。
这是一个包含 3 个文件的简单示例
- C# 中的 DLL
- C++/CLR 中的接口程序
- C++主程序
首先是 C# DLL。 这将构建为 DLL。
using System;
using System.Collections.Generic;
using System.Text;
namespace csdll
{
public class ReturnValues
{
public void CSGetInt(ref int x)
{
x = 42;
}
public void CSGetStr(ref string s)
{
s = "Hey it works";
}
}
}
现在是接口程序。 这就是胶水逻辑。 这必须编译为 C++/CLR,但可以与 main 位于同一项目中:只是不在同一文件中,因为它必须以不同的方式编译。 在"公共语言运行时支持中的常规"下,选择"公共语言运行时支持 (/clr)"。
#include <string>
#include <msclrmarshal_cppstd.h>
#using "csdll.dll"
using namespace System;
extern void cppGetInt(int* value)
{
csdll::ReturnValues^ rv = gcnew csdll::ReturnValues();
rv->CSGetInt(*value);
}
extern void cppGetStr(std::string& value)
{
System::String^ csvalue;
csdll::ReturnValues^ rv = gcnew csdll::ReturnValues();
rv->CSGetStr(csvalue);
value = msclr::interop::marshal_as<std::string>(csvalue);
}
现在是主程序。
#include "stdafx.h"
#include <iostream>
#include <string>
// These can go in a header
extern void cppGetInt(int* value);
extern void cppGetStr(std::string& value);
int _tmain(int argc, _TCHAR* argv[])
{
int value = 99;
std::string svalue = "It does not work";
cppGetInt(&value);
std::cout << "Value is " << value << std::endl;
cppGetStr(svalue);
std::cout << "String value is " << svalue << std::endl;
return 0;
}
将依赖项设置为 DLL。将生成平台设置为混合平台,而不是 win32 或任何 CPU。 如果将其设置为其中任何一个,则不会构建某些内容。 运行它,你会得到
Value is 42
String value is Hey it works
相关文章:
- 为什么导入Mixed native/CLR lib.dll的本机C++应用程序没有在Mixed lib.dll中的外部变
- 如何在 64 位 vb.net Windows 应用程序中引用 32 位 dll
- C# DLL 从C++应用程序调用 SOAP Web 服务
- 将 c++ 生成器应用程序与外部 dll 结合使用
- WinDeployqt 不会为调试应用程序部署 Qwindowsd.dll
- Log4net,将日志消息从 c++ dll 发送到 c# 应用程序?
- 调试 ASP MVC 应用程序中使用的C++ DLL
- Qt应用程序找不到第三方DLL并崩溃
- 如何将从控制台应用程序C++回调设置为C++ COM DLL
- 我可以用C++/WinRT编写一个DLL,供windows桌面应用程序(而不是UWP)或Unity插件使用吗
- .NET核心应用程序无法加载C++DLL
- 在通用 Windows 应用程序C++上使用 win32 DLL 库
- 从 C# Windows 应用程序调用 C dll 会导致 svchost.exe 崩溃
- 使用 C++ dll 运行 c# 应用程序会生成无法加载异常
- 为什么我的 C# 应用程序无法加载我的 C++ dll?
- 应用程序仅在qt调试器中加载dll,而不是独立加载
- 如果在 DLL 和调用应用程序中使用 GPGPU API,会发生什么情况
- C++ XE 5 应用程序和C++生成器 5 dll 兼容性
- Cygwin1.dll c++ 应用程序错误
- 在线更新DLL应用程序