为了简化问题,这里是我尝试从调用的本机方法。NET类。
[NativeDll.dll]
收割台
typedef struct _ADDRESS {
LPWSTR City;
} ADDRESS, *PADDRESS;
typedef struct _ADDRESS_SET {
ULONG AddressCount;
PADDRESS AddressList;
} ADDRESS_SET, *PADDRESS_SET;
DWORD WINAPI
GetAddressSet(_Outptr_ ADDRESS_SET **AddressSet);
VOID WINAPI
FreeAddressSet(__in ADDRESS_SET *AddressSet);
C++实现
DWORD WINAPI
GetAddressSet(_Outptr_ ADDRESS_SET **AddressSet) {
HRESULT hr = ERROR_SUCCESS;
const int totalRecords = 2;
LPCWSTR cities[totalRecords] = { L"City 1", L"City 2"};
ADDRESS *addresses = (ADDRESS*)malloc(sizeof(ADDRESS) * totalRecords);
for (int i = 0; i < totalRecords; i++) {
addresses[i].City = (wchar_t*)malloc((wcslen(cities[i]) + 1) * sizeof(wchar_t));
addresses[i].City = (LPWSTR)cities[i];
}
ADDRESS_SET *recordSet = (ADDRESS_SET*)malloc(sizeof(ADDRESS_SET));
recordSet->AddressCount = totalRecords;
recordSet->AddressList = addresses;
*AddressSet = recordSet;
return ERROR_SUCCESS;
}
VOID WINAPI
FreeAddressSet(__in ADDRESS_SET *AddressSet) {
if (AddressSet != NULL) {
if (AddressSet->AddressList != NULL) {
for (int i = 0; i < AddressSet->AddressCount; i++) {
if (AddressSet->AddressList[i].City != NULL) {
free(AddressSet->AddressList[i].City);
AddressSet->AddressList[i].City = NULL;
}
}
free(AddressSet->AddressList);
AddressSet->AddressList = NULL;
}
free(AddressSet);
AddressSet = NULL;
}
}
当我尝试从本机代码调用这些API时,我能够获得地址数组。但是AV当我尝试释放城市字符串(LPWSTR)时。
这是我的C代码。
[StructLayout(LayoutKind.Sequential)]
internal struct ADDRESS {
internal IntPtr City;
}
[StructLayout(LayoutKind.Sequential)]
internal struct ADDRESS_SET {
internal UInt32 AddressCount;
internal IntPtr AddressList;
}
internal class NativeMethods {
[DllImport("nativedll.dll", EntryPoint = "GetAddressSet")]
internal static extern UInt32 GetAddressSet(ref IntPtr AddressSet);
[DllImport("nativedll.dll", EntryPoint = "FreeAddressSet")]
internal static extern UInt32 FreeAddressSet([In] IntPtr AddressSet);
}
class Program {
static void Main(string[] args) {
IntPtr pAddressSet = IntPtr.Zero;
UInt32 returnStatus = NativeMethods.GetAddressSet(ref pAddressSet);
if(returnStatus == 0 && pAddressSet != IntPtr.Zero) {
ADDRESS_SET addressSet = Marshal.PtrToStructure<ADDRESS_SET>(pAddressSet);
UInt32 addressCount = addressSet.AddressCount;
IntPtr addressList = addressSet.AddressList;
if (addressCount != 0 && addressList != IntPtr.Zero) {
for (int i = 0; i < addressCount; i++) {
ADDRESS address = Marshal.PtrToStructure<ADDRESS>(addressList);
addressList += Marshal.SizeOf(typeof(ADDRESS));
Console.WriteLine($"City: {Marshal.PtrToStringUni(address.City)}");
}
}
}
NativeMethods.FreeAddressSet(pAddressSet);
}
}
在本例中,地址结构中的City字段为IntPtr。我也尝试将City字段设置为[marshallas(UnmanagedType.LPWStr)]字符串,但未能成功释放。我不确定我的错误是什么。NET代码。