[CP-SAT] fix memory leak in C#

This commit is contained in:
Laurent Perron
2022-01-20 13:30:34 +01:00
parent f481aa23a9
commit 58659bd77e
3 changed files with 21 additions and 3 deletions

View File

@@ -13,12 +13,19 @@
%include "ortools/base/base.i"
%include "stdint.i"
%include "std_string.i"
%{
#include "ortools/init/init.h"
%}
%typemap(ctype) uint8_t* "uint8_t*"
%typemap(imtype) uint8_t* "System.IntPtr"
%typemap(cstype) uint8_t* "System.IntPtr"
%typemap(csin) uint8_t* "$csinput"
%typemap(in) uint8_t* %{ $1 = $input; %}
%ignoreall
%unignore operations_research;
@@ -38,6 +45,7 @@
%unignore operations_research::CppBridge::ShutdownLogging;
%unignore operations_research::CppBridge::SetFlags;
%unignore operations_research::CppBridge::LoadGurobiSharedLibrary;
%unignore operations_research::CppBridge::DeleteByteArray;
%unignore operations_research::OrToolsVersion;
%unignore operations_research::OrToolsVersion::MajorNumber;

View File

@@ -14,6 +14,7 @@
#ifndef OR_TOOLS_OPEN_SOURCE_INIT_INIT_H_
#define OR_TOOLS_OPEN_SOURCE_INIT_INIT_H_
#include <cstdint>
#include <string>
#include <vector>
@@ -123,6 +124,14 @@ class CppBridge {
static bool LoadGurobiSharedLibrary(const std::string& full_library_path) {
return LoadGurobiDynamicLibrary({full_library_path}).ok();
}
/**
* Delete a temporary C++ byte array.
*/
static void DeleteByteArray(uint8_t* buffer) {
delete [] buffer;
}
};
class OrToolsVersion {

View File

@@ -76,10 +76,10 @@
%typemap(csout) CppProtoType {
System.IntPtr data = $imcall;
int size = System.Runtime.InteropServices.Marshal.ReadInt32(data);
data += sizeof(int);
System.IntPtr bufferStart = data + sizeof(int);
byte[] buf = System.Buffers.ArrayPool<byte>.Shared.Rent(size);
System.Runtime.InteropServices.Marshal.Copy(data, buf, 0, size);
// TODO(user): delete the C++ buffer.
System.Runtime.InteropServices.Marshal.Copy(bufferStart, buf, 0, size);
Google.OrTools.Init.CppBridge.DeleteByteArray(data);
try {
return CSharpProtoType.Parser.ParseFrom(System.MemoryExtensions.AsSpan(buf, 0, size));
} catch (Google.Protobuf.InvalidProtocolBufferException /*e*/) {
@@ -98,4 +98,5 @@
$result[2] = (size >> 16) & 0xFF;
$result[3] = (size >> 24) & 0xFF;
}
%enddef // end PROTO2_RETURN