Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have exported a C++ method to C# and using list of structure in both the places. But when i am inserting the list from C++ to C# method it throws me write access violation. Below is the code reference.

What I have tried:

C++ Code:
.h File:
struct DBAData
{
long id;
char name;

--
--
}

.Cpp file:
extern "C" __declspec(dllexport) void __cdecl TableData(std::list<DBAData> ReturnData)
	{
		
		std::list<DBAData> eventDB;
		
		GetTableData(4, eventDB);
		
		std::copy(eventDB.begin(), eventDB.end(),
			std::back_insert_iterator<std::list<DBAData> >(ReturnData));// Fails here
}



C# Code:

cs file:
public struct Data
    {
        public long id;
        public char name;
--
--
--
    }

    public class Test
    {
        [DllImport("Data.DLL")]
         public static extern void TableData(IList<Data> return)
    }

void function()
{
 IList<Data> retValue = new List<Data>();
 Test.TableData(retValue);
}



First thing can we map list<structure> from C++ to Ilist<structure> in C# , as i need to export list of data from C++ to C#. Or is there any other best way to do it.

Thanks in Advance.
Posted
Updated 6-Apr-21 5:45am

As far as I'm aware you can't marshall something like a list, because these sorts of objects are implemented differently across C# and C++. You need to instead look at returning or consuming something much simpler, like an array instead. I'd recommend having the C++ method require an array of Data and also provide an int indicating the length of the array. You could then convert it into a list within the C++ method to perform whatever operations you need.

c++ - How to return a list in C# using P/Invoke? - Stack Overflow[^]
 
Share this answer
 
I am willing to bet it's because you are trying to store a name in a single char. Of course, I could be wrong.

That's just one issue though. Solution 1 outlined the bigger problem you have and possible work-around. Once you have done that then you will have to deal with the name issue.
 
Share this answer
 

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