FFI/MemoryPointer内存分配

Lev*_*evi 4 c++ ruby windows ffi

我肯定错过了什么.我一直在读FFI,似乎无法得到明确的答案.假设我有以下C++函数:

extern "C" {
  int ReturnAnArrayOfStrings(const char* arrayOfStrings[]) {
    if( NULL == arrayOfStrings ) return someCharList.size();

    for(auto iter = someCharList.begin(), auto index = 0; iter != someCharList.end(); ++iter, ++index) {
        char* allocatedHere = new char[strlen(*iter)]; // note that this is not freed
        strcpy_s(allocatedHere, strlen(*iter), *iter);
        arrayOfStrings[index] = allocatedHere;
    }

    return someCharList.size();
  }
}
Run Code Online (Sandbox Code Playgroud)

据我所知,如果从FFI使用此功能,您只需执行以下操作:

module SomeDll
  extend FFI::Library
  ffi_lib 'SomeDll.dll'
  attach_function :get_strings, :ReturnAnArrayOfStrings, [:pointer], :int
end

include SomeDll
pointer = FFI::MemoryPointer.new :pointer, get_strings(nil)  # how many strings are there?
get_strings pointer
pointer.get_array_of_string(0).each do |value|
  puts value
end
Run Code Online (Sandbox Code Playgroud)

我的问题是:谁清理记忆?C++方法正在new使用char*,但永远不会释放它.FFI会处理这个吗?我在这里错过了什么?

提前致谢.

小智 5

Ruby FFI尝试对谁拥有内存进行对称 - 如果你分配它(即C代码),你必须释放它.相反,如果FFI分配它,它就可以释放它.

你没有发布你的FreeStrings()函数,但假设它看起来有点像:

void FreeStringArray(char **strings, int len) {
    for (int i = 0; i < len; ++i) {
        delete[] strings[i];
    }
    // Do _NOT_ free 'strings' itself, that is managed by FFI
}
Run Code Online (Sandbox Code Playgroud)

你这样使用它:

module SomeDll
  extend FFI::Library
  ffi_lib 'SomeDll.dll'
  attach_function :get_strings, :ReturnAnArrayOfStrings, [:pointer], :int
  attach_function :free_strings, :FreeStringArray, [ :pointer, :int ], :void
end

include SomeDll

count = get_strings(nil)
strings = FFI::MemoryPointer.new :pointer, count
get_strings strings
strings.get_array_of_string(0, count).each do |value|
  puts value
end

# free each element of the array
free_strings(strings, count)
Run Code Online (Sandbox Code Playgroud)

那应该有用.

等效的C代码是:

int count = ReturnArrayOfStrings(NULL);

// Allocate an array for the pointers.  i.e. FFI::MemoryPointer.new :pointer, count
char **ptr_array = (char **) calloc(count, sizeof(char *));

ReturnArrayOfStrings(ptr_array);
for (int i = 0; i < count; ++i) {
    printf("string[%d]=%s\n", i, ptr_array[i]);
}

// Free each element of the array (but not the array itself)
FreeStringArray(ptr_array, count);

// free the array itself. i.e FFI::MemoryPointer garbage-collecting its  memory
free(ptr_array);
Run Code Online (Sandbox Code Playgroud)