业务中开发需要提供c++的C#开发的dll,通过com组件的方式实现
c#代码 com组件方式
ComDll代码生成的dll ,选择 项目 属性 生成 目标平台 x64生成,把dll放到c++debug下面
namespace ComDll
{
public interface IAddService
{
string Add(int a, int b);
}
}
using System;
using System.Net.Http;
namespace ComDll
{
public class AddService
{
public static string sss = "00";
public string Add(int a, int b)
{
using (var httpClient = new HttpClient())
{
string url = $"http://192.168.0.57:11223/addserver?arr1={a}&arr2={b}";
var response = httpClient.GetAsync(url).Result;
response.EnsureSuccessStatusCode();
return response.Content.ReadAsStringAsync().Result;
}
}
}
}
测试的代码
using Microsoft.AspNetCore.Mvc; namespace WebApi.Controllers; [ApiController] [Route("")] public class AddController : ControllerBase { [HttpGet("addserver")] public string AddServer(string arr1, string arr2) { return $"成功调用 http://192.168.0.57:11223/addserver?arr1={arr1}&arr2={arr2}"; } }
c++代码
项目引用添加c# dll

debug x64
#include <iostream>
#include <string>
#include <msclr/marshal_cppstd.h>
using namespace System;
using namespace msclr::interop;
int main(array<System::String^>^ args)
{
String^ originalValue = ComDll::AddService::sss;
std::cout << "原本值 sss value: " << msclr::interop::marshal_as<std::string>(originalValue) << std::endl;
ComDll::AddService::sss = "123";
String^ modifiedValue = ComDll::AddService::sss;
std::cout << "修改的值 sss value: "<< msclr::interop::marshal_as<std::string>(modifiedValue)<< std::endl;
ComDll::AddService^ service = gcnew ComDll::AddService();
int a = 10, b = 20;
String^ result = service->Add(a, b);
std::cout << "C# Add 方法返回值: " << msclr::interop::marshal_as<std::string>(result) << std::endl;
return 0;
}
运行效果

浙公网安备 33010602011771号