0

I return a string array from C++ function and want to use this string array in C#. When i try to get the array from C# it gives me this error:

System.Runtime.InteropServices.MarshalDirectiveException: "Cannot marshal 'return value': Invalid managed/unmanaged type

Here is my C++ code:

Header

#pragma once

#ifdef CRITELAB_EXPORTS
#define API __declspec(dllexport)
#else
#define  API __declspec(dllimport)
#endif

#include <string>


extern "C" API std::string* gatherInfos();

CPP

std::string* gatherInfos()
{
    std::string username;
    std::string password;
    
    puts("Please enter a username:");
    fflush(stdout);
    std::cin >> username;
    std::cout << std::endl;

    puts("Please enter a password:");
    fflush(stdout);
    std::cin >> password;

    std::string* const gatheredInfos = new std::string[2];
    gatheredInfos[0] = username;
    gatheredInfos[1] = password;

    return gatheredInfos;
}

And here is my C# code

using System;
using System.Runtime.InteropServices;

namespace ConsoleApp1
{
    internal class Program
    {
        private static void Main(string[] args)
        {

            string[] gatheredInfos = gatherInfos();    
            Console.ReadLine();
        }


        [DllImport("critelab.dll")]
        public static extern int connectToDB();

        [DllImport("critelab.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern string[] gatherInfos();
    }
}
chrischtel
  • 11
  • 2
  • 6
  • 2
    A `std::string` is not similar to a C# `string`, other than in name. – ChrisMM May 15 '21 at 21:11
  • So do I have to convert it? And how? – chrischtel May 15 '21 at 21:13
  • Is your c++ code managed (cli) or no? – ChrisMM May 15 '21 at 21:15
  • I think the code is unmanaged. – chrischtel May 15 '21 at 21:17
  • Does this answer your question? [Returning a std::string from a C++ DLL to a c# program -> Invalid Address specified to RtlFreeHeap](https://stackoverflow.com/questions/799076/returning-a-stdstring-from-a-c-dll-to-a-c-sharp-program-invalid-address-s) – ChrisMM May 15 '21 at 21:20
  • 2
    You can't return a `std::string`, but you can return a `char *` then convert that in C# to a `string` – ChrisMM May 15 '21 at 21:21
  • Does this answer your question? [std::string in C#?](https://stackoverflow.com/questions/874551/stdstring-in-c) – Charlieface May 15 '21 at 21:31
  • See [Marshaling Different Types of Arrays](https://learn.microsoft.com/en-us/dotnet/framework/interop/marshaling-different-types-of-arrays). Also see [Marshaling Strings](https://learn.microsoft.com/en-us/dotnet/framework/interop/marshaling-strings) and [Default Marshaling for Strings](https://learn.microsoft.com/en-us/dotnet/framework/interop/default-marshaling-for-strings) – Alexander Petrov May 15 '21 at 22:28

0 Answers0