情况是,我包装c# dll在c++项目中使用它,当我执行c++项目时,我看不到任何关于内存泄漏的迹象,但内存一点一点地增加。我认为这是因为c#库中的GC在c++项目中不起作用,我不知道如何解决它。请帮帮我。
我的代码如下:
c# using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace CSharpLib
{
[Guid("8EA9EAA8-CA3D-4584-B1E0-7B9561757CA4")]
public interface ICSharpLibrary
{
int[] GetData();
string GetName();
bool Init();
}
[Guid("B62A2B51-621D-41AA-8F4F-021E404B593C")]
public class CSharpLibrary : ICSharpLibrary, IDisposable
{
private bool disposed = false;
private int[] data;
private string name = "CSharpLib";
private SafeHandle safeHandle = new SafeFileHandle(IntPtr.Zero, true);
private void MakeData()
{
var list = new List<int>();
var rnd = new Random();
for(var i = 0; i < 1000; i++)
{
list.Add(rnd.Next(0, 255));
}
data = list.ToArray();
}
public int[] GetData()
{
MakeData();
return data;
}
public string GetName()
{
return name;
}
public bool Init()
{
data = null;
return true;
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
{
return;
}
if (disposing)
{
data = null;
safeHandle.Dispose();
}
disposed = true;
}
}
}
- c++
- 执行人
#pragma once
#ifdef CPLUSLIBRARY_EXPORTS
#define CPLUSLIBRARY_API __declspec(dllexport)
#else
#define CPLUSLIBRARY_API __declspec(dllimport)
#endif
extern "C" CPLUSLIBRARY_API bool Init();
extern "C" CPLUSLIBRARY_API int* GetData();
extern "C" CPLUSLIBRARY_API char* GetName();
#include <Windows.h>
#include "pch.h"
#include "CPlusLibrary.h"
#import "lib/CSharpLibrary.tlb" no_namespace named_guids
ICSharpLibrary* lib = NULL;
int* data = NULL;
bool isWorking = false;
char* name = NULL;
bool Init() {
HRESULT hr = CoInitializeEx(NULL, tagCOINIT::COINIT_MULTITHREADED);
if (!SUCCEEDED(hr))
return false;
hr = CoCreateInstance(CLSID_CSharpLibrary, NULL, CLSCTX_INPROC_SERVER, IID_ICSharpLibrary, reinterpret_cast<void**>(&lib));
if (!SUCCEEDED(hr))
return false;
return true;
}
int* GetData() {
auto raw = lib->GetData();
void* pVoid = NULL;
HRESULT hr = ::SafeArrayAccessData(raw, &pVoid);
if (!SUCCEEDED(hr))
return NULL;
auto result = reinterpret_cast<int*>(pVoid);
return result;
}
char* GetName() {
char str[10];
strcpy_s(str, lib->GetName());
name = str;
return name;
}
#include <iostream>
#include <CPlusLibrary.h>
#include <CoreWindow.h>
int main()
{
if (!Init())
return 0;
while (true) {
auto name = GetName();
std::cout << name << std::endl;
auto data = GetData();
for (int i = 0; i < 1000; i++) {
std::cout << data[i];
}
std::cout << std::endl;
Sleep(100);
}
}
来自SafeArrayAccessData文档
调用SafeArrayAccessData后,必须调用SafeArrayUnaccessData函数来解锁数组
不确定这是泄漏的实际原因。但是在调试问题时,良好的第一步是确保您遵循了文档中指定的所有规则。