C ++で作成された構造体Foo
のアンマネージ配列からC#でオブジェクトを作成したいと思います。Foo
これは私がそれが機能するはずだと思う方法です:
C ++側:
extern "C" __declspec(dllexport) void* createFooDetector()
{
return new FooDetector();
}
extern "C" __declspec(dllexport) void releaseFooDetector(void* fooDetector)
{
FooDetector *fd = (FooDetector*)fooDetector;
delete fd;
}
extern "C" __declspec(dllexport) int detectFoo(void* fooDetector, Foo **detectedFoos)
{
FooDetector *fd = (FooDetector*)fooDetector;
vector<Foo> foos;
fd->detect(foos);
int numDetectedFoos = foos.size();
Foo *fooArr = new Foo[numDetectedFoos];
for (int i=0; i<numDetectedFoos; ++i)
{
fooArr[i] = foos[i];
}
detectedFoos = &fooArr;
return numDetectedFoos;
}
extern "C" __declspec(dllexport) void releaseFooObjects(Foo* fooObjects)
{
delete [] fooObjects;
}
C#側:(読みやすくするためにC#内からC ++関数を呼び出すことができるようにするいくつかの凝ったコードを省略しました);
List<Foo> detectFooObjects()
{
IntPtr fooDetector = createFooDetector();
IntPtr detectedFoos = IntPtr.Zero;
detectFoo(fooDetector, ref detectedFoos);
// How do I get Foo objects from my IntPtr pointing to an unmanaged array of Foo structs?
releaseFooObjects(detectedFoos);
releaseFooDetector(fooDetector);
}
しかし、からオブジェクトを取得する方法がわかりませんIntPtr detectedFoos
。どういうわけか可能であるはずです...何かヒントはありますか?
アップデート
Foo
が単純な検出長方形であると仮定しましょう。
C ++:
struct Foo
{
int x;
int y;
int w;
int h;
};
C#:
[StructLayout(LayoutKind.Sequential)]
public struct Foo
{
public int x;
public int y;
public int width;
public int height;
}
アンマネージメモリを解放する前に、アンマネージメモリから読み取り、そこから新しいマネージオブジェクトを作成することはできますか?
オブジェクトがどのようFoo
に検出されるかわからないので、を呼び出す前にC#で割り当てるメモリの量がわかりませんdetectFoo()
。そのため、C ++でメモリを割り当て/解放し、それにポインタを渡すだけです。detectedFoo
しかし、どういうわけか、C#でsポインタアドレスを取得できません。それ、どうやったら出来るの?