Click here to Skip to main content
15,914,452 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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)
{
    // Replace "-" to " "
    int len = strlen(strTB);
    for (int i = 0; i < len; i++)
        if (strTB[i] == '-')
            strTB[i] = ' ';

    // Split to int data !
    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 !
Posted
Updated 30-Apr-21 8:50am
Comments
Rick York 30-Apr-21 16:59pm    
Have you considered having the C# side own the vector and passing a reference to it to the DLL?

I have no idea if that's actually feasible so I am asking you.
Richard MacCutchan 1-May-21 4:14am    
I do not think you can pass std::types to C# as their structure is not compatible. Most likely it would be easier for the calling routine to pass the address of an array to the DLL. The C++ code can then fill the array with the numbers.

1 solution

 
Share this answer
 
Comments
Volga_ 30-Apr-21 15:00pm    
This is not to help me. I do not see the good answer in that topic ! What do you think about for my topic? Thanks.
[no name] 1-May-21 12:56pm    
You create an "array interface" to your vector in the c++ dll (I know, one more step); marshall the array to c#; convert the array to a generic list (oh no! Another step!)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900