i have a problem in pinvoking a vector containing struct to c#
i cannot marshal intptr to string in struct
for (int i = 0; i < itemcount; i++)
{
var soft = items[i];
string x = Marshal.PtrToStringAuto( soft.DisplayName);
}
please help
What I have tried:
c++ code
typedef intptr_t ItemListHandle;
bool GetPrograms(InstalledPrograms::ItemListHandle * hItems, Software** itemsFound, int* itemCount)
{
vector<Software>* lst = InstalledPrograms::GetInstalledPrograms(true);
*hItems = reinterpret_cast<InstalledPrograms::ItemListHandle>(lst);
*itemsFound = lst->data();
*itemCount = lst->size();
return true;
}
c# code
class ItemsSafeHandle : SafeHandleZeroOrMinusOneIsInvalid
{
public ItemsSafeHandle()
: base(true){}
protected override bool ReleaseHandle()
{
return Program.ReleaseItems(handle);
}
}
[StructLayout(LayoutKind.Sequential)]
public struct Software
{
public IntPtr DisplayName;
public IntPtr InstallLocation;
public IntPtr Version;
public IntPtr Architecture;
public IntPtr Icon;
};
class Program
{
[DllImport(@"mydll.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "GetPrograms",CharSet =CharSet.Auto)]
static unsafe extern bool GetPrograms(out ItemsSafeHandle itemsHandle, out Software* items, out int itemCount);
[DllImport(@"mydll.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ReleaseVectorItems", CharSet = CharSet.Auto)]
public static unsafe extern bool ReleaseItems(IntPtr itemsHandle);
static unsafe void Main(string[] args)
{
int itemcount = 0;
Software* items;
using (GenerateItemsWrapper( out items, out itemcount))
{
for (int i = 0; i <itemcount; i++)
{
var soft = items[i];
string x = Marshal.PtrToStringAuto(soft.DisplayName);
}
}
}
static unsafe ItemsSafeHandle GenerateItemsWrapper(out Software* items, out int itemsCount)
{
ItemsSafeHandle itemsHandle;
if (!GetPrograms(out itemsHandle, out items, out itemsCount))
{
throw new InvalidOperationException();
}
return itemsHandle;
}