【发布时间】:2021-04-12 11:04:24
【问题描述】:
我想在 C++ 和 C# 中使用 DLL 中的函数。
我将字符串数据存储在向量中。
我的 C++ 文件包含:
#include "stdafx.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
extern "C" __declspec(dllexport) std::vector<std::string> GetProduct();
std::vector<std::string> GetProduct()
{
std::vector<std::string> vectProduct;
vectProduct.push_back("Citroen");
vectProduct.push_back("C5");
vectProduct.push_back("MOP-C5");
return vectProduct;
}
在 C# 中
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
namespace ConsoleApplication
{
class Program
{
[DllImport("ProductLibrary.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern StringBuilder GetProduct();
static void Main(string[] args)
{
StringBuilder vectProduct_impl = GetProduct();
}
}
}
我不知道如何在c#中继续浏览数组。 我不知道使用矢量是否最佳。如果您有其他解决方案,我准备好了。
请帮忙。
【问题讨论】:
-
不要尝试从为其他项目编译的 DLL 中导出 C++ 数据结构。 C++ 没有明确定义的 ABI,这意味着根据定义这是未定义的行为。开始:stackoverflow.com/a/33801580/4043866 正如该线程中所说,您要么必须导出 C 接口,要么使用其他技术,如 COM 或 C++/CLI。
-
JulianH 所说的... 作为旁注,对于
std::vector和std::string,您可以获得内部“数据”的 C 指针,但如果您“混合”它们两者然后一切顺利...... -
另一个问题:如果内存是从 C/C++ 端分配的,释放它通常很复杂......但最大的问题是 为什么 你要混合两种语言本身就是完整的......学习天空或学习滑冰。不要试图同时做这两件事,除非是真的 真的 真的必要
-
请问有没有可能使用其他东西来存储字符串数据并在 C# 中获取它。我尝试创建另一个返回类型为 int* 的函数。我也使用 IntPtr 来获取 ptr 的数据。但是我没有到达字符串类型。
-
@TheRight 一切皆有可能。在风险和回报之间总是有交易要做。