2013-05-02 35 views
1

可以說,我在C以下結構移動結構數據

typedef struct 
{ 
    int field1; 
    char field2[16]; 
} MYSTRUCT; 

現在我有一個C程序被調用的指針MYSTRUCT,我需要填充的結構,例如,

int MyCall(MYSTRUCT *ms) 
{ 
    char *hello = "hello world"; 
    int hlen = strlen(hello); 
    ms->field1 = hlen; 
    strcpy_s(ms->field2,16,hello); 
    return(hlen); 
} 

我該如何在C#中編寫MyCall?我曾在Visual Studio 2010中嘗試過這種方法:

... 
using System.Runtime.InteropServices; 
[StructLayout(LayoutKind.Explicit)] 
public struct MYSTRUCT 
{ 
    [FieldOffset(0)] 
    UInt32 field1; 
    [FieldOffset(4)] 
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] 
    string field2; 
} 

public int MyProc(ref MYSTRUCT ms) 
{ 
    string hello = "hello world"; 
    int hlen = hello.Length; 
    Marshal.Copy(hello, ms.field2, 0, hlen); // doesn't work 
    Array.Copy(hello, ms.field2, hlen);  // doesn't work 
    // tried a number of other ways with no luck 
    // ms.field2 is not a resolved reference 
    return(hlen); 
} 

感謝您提供正確方法的任何提示。

+0

'ms.field2 = hello;',但你可能正在尋找別的東西。顯示調用'MyProc'的代碼可能有用...... – 2013-05-02 01:34:05

+0

我也注意到你的C中的結果是int類型的,而不是unsigned int,所以在C#中,如果你是用C#的話,你可能想讓你的數據類型Int32代替UInt32 – 2013-05-02 01:51:06

+0

將程序移植到C#中不必使用結構佈局,並且如果要通過引用傳遞結構,則可能會使它成爲一個類,因爲它通過引用傳遞。然後,您可以根據需要分配您的值。現在,如果您的功能正在導出到動態庫,那麼您通過使用結構化佈局可以取得很好的效果。 – 2013-05-02 01:53:19

回答

3

嘗試更改StructLayout。

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] 
public struct MYSTRUCT 
{ 
    public UInt32 field1; 
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] 
    public string field2; 
} 

因爲,你傳遞作爲參考,你嘗試將其設置爲:

public int MyProc(ref MYSTRUCT ms) 
{ 
    string hello = "hello world"; 
    ms.field2 = hello; 
    return hello.Length; 
} 

當使用關鍵字ref,你會打電話給MyProc像這樣:

static void Main(string[] args) 
{ 
    var s = new MYSTRUCT(); 
    Console.WriteLine(MyProc(ref s)); // you must use "ref" when passing an argument 
    Console.WriteLine(s.field2); 
    Console.ReadKey(); 
} 
+0

謝謝!儘管Appaprently我必須指定「公共字符串field2」即使MYSTRUCT是公開的。否則由於保護級別而無法訪問。 – 2013-05-02 09:18:58

+0

我越來越近,但它似乎不喜歡「ref MYSTRUCT」。我假設這是告訴C#它正在接收一個指向結構的指針,對嗎?如果不是,那麼宣佈它的正確方法是什麼? – 2013-05-02 18:50:51

+0

@Neilw,是的「ref」關鍵字是必不可少的指向結構的指針。你打電話給MyProf的過程如何?你有什麼錯誤嗎? – 2013-05-02 19:22:43