0

C++ DLL に渡す必要がある C# の構造があります。

typedef struct
{
    TDate  fDate;
    double fRate;
} TRatePt;

typedef struct _TCurve2
{
    int       fNumItems;     /* Number of TRatePts in fArray */
    TRatePt  *fArray;        
    TDate     fBaseDate;     
} TCurve2;

以下は、C# で作成した構造です。

[StructLayout(LayoutKind.Sequential), Serializable]
public struct TRatePt
{
    public int fDate;
    public double fRate;
}

[StructLayout(LayoutKind.Sequential), Serializable]
public struct TCurve2
{
    public int fNumItems;
    public IntPtr fArray;
    public int fBaseDate;
}

C DLL に簡単なメソッドがあります。

EXPORT int TestMethodForZC(TCurve2 *discCurve)
{
    printf("\n\nIn TestMethodForZC\n");
    printf("discCurve->fBaseDate = %d\n\n\n",discCurve->fBaseDate );
    return 0;
}

そして、私は PInvoke を使用して、次のように呼び出しています。

[DllImport("clibrary.dll", EntryPoint = "TestMethodForZC", , CallingConvention = CallingConvention.Cdecl)]
private static extern int _TestMethodForZC(ref TCurve2 discCurve);

TRatePt のマーシャリング:

 TRatePt[] items = new TRatePt[2];
 items[0].fDate = 200;
 items[1].fDate = 300;

 items[0].fRate = 0.2d;
 items[1].fRate = 0.3d;
 TCurve2 tc2 = new TCurve2() { fBaseDate = 12000, fNumItems = 2 };

 tc2.fNumItems = items.Length;
 tc2.fArray = Marshal.AllocHGlobal(items.Length * Marshal.SizeOf(typeof(TRatePt)));

 IntPtr item = tc2.fArray;
 for (int i = 0; i < items.Length; i++)
 {
     Marshal.StructureToPtr(items[i], item, false);
     item = new IntPtr(item.ToInt32() + Marshal.SizeOf(typeof(TRatePt)));
     }

 _TestMethodForZC(ref tc2);

TRatePt を手動でマーシャリングし、IntPtr をメソッドに渡していますが、ジャンク値を出力しています。マーシャリングで Int32 と Int64 を試しましたが、違いはありません。私は何か間違ったことをしていますか?助言がありますか?

PS:私はこの質問をstackoverflowで検索しようとしましたが、かなりの議論があったものを見つけましたが、提案はどれもうまくいきませんでした.

4

0 に答える 0