Hello,
I have used return of function with std::vector<int> from C++ dll to C#.
1. C++ dll code file:
#include "pch.h"
#include <vector>
std::vector<int> _stdcall f(char* strTB)
{
int len = strlen(strTB);
for (int i = 0; i < len; i++)
if (strTB[i] == '-')
strTB[i] = ' ';
std::vector<int> ret;
char separators[] = " ";
char* token;
char* next_token;
int i = 0;
token = strtok_s(strTB, separators, &next_token);
while (token)
{
ret.push_back(atoi(token));
token = strtok_s(NULL, separators, &next_token);
}
return ret;
}
2. .def file for compile DllTest.dll:
EXPORTS
f
Compile to dll successful !
3. C# code file using function f() from DllTest.dll.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace ConsoleAppCSharp
{
class Program
{
[DllImport("DllTest.dll", CharSet = CharSet.Ansi)]
static extern List<int> f(string str);
static void Main(string[] args)
{
string str = "12 - 34 56 78";
List<int> ret = f(str);
int n = ret.Count;
for (int i = 0; i < n; i++)
Console.WriteLine(ret[i]);
Console.ReadKey();
}
}
}
Error was displayed when compile with C#:
System.Runtime.InteropServices.MarshalDirectiveException: 'Cannot marshal 'return value': Generic types cannot be marshaled.'
I can't know how to fix code C#. Help me. Thanks.
What I have tried:
I try to write code and to compile, but not get result !