如何在 C 应用程序中使用 C# DLL

How to use a C# DLL in a C application?

本文关键字:DLL 应用程序      更新时间:2023-10-16

我有 C# DLL,我在 COM 互操作的帮助下C++使用该 DLL,方法是在我的.cpp文件中导入相应的.tlb文件#import "com.MyIntrop.tlb"并且它工作得非常好。

现在我想在我的 C 代码中使用相同的 DLL,但由于我不能在 C 中使用#import如何使用我在 C 中注册为 COM 程序集的相同 DLL。

这是一个包含 3 个文件的简单示例

  1. C# 中的 DLL
  2. C++/CLR 中的接口程序
  3. 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