2010-02-08 3 views
4

Я полностью новичок в C# и нуждаюсь в помощи, преобразующей структуру C++ в C#. Структура C++ определяется как:Помогите мне преобразовать структуру C++ в C#

#define QUE_ADDR_BUF_LENGTH 50 
#define QUE_POST_BUF_LENGTH 11 

typedef struct 
    { 
    const WCHAR *streetAddress; 
    const WCHAR *city; 
    const WCHAR *state; 
    const WCHAR *country; 
    const WCHAR *postalCode; 
} QueSelectAddressType; 

typedef struct 
    { 
    WCHAR streetAddress[QUE_ADDR_BUF_LENGTH + 1]; 
    WCHAR city[QUE_ADDR_BUF_LENGTH + 1]; 
    WCHAR state[QUE_ADDR_BUF_LENGTH + 1]; 
    WCHAR country[QUE_ADDR_BUF_LENGTH + 1]; 
    WCHAR postalCode[QUE_POST_BUF_LENGTH + 1]; 
    } QueAddressType; 

Я не могу внести изменения в структуру C++, поскольку они определяются API я пытающегося интерфейс с. Любая помощь будет оценена по достоинству.

EDIT: Здесь больше информации, функция в DLL я пытающегося позвонить объявлен следующим образом:

#ifdef QUEAPI_EXPORTS 
#define QueAPIExport __declspec(dllexport) 
#elif defined QUEAPI_SERVER 
#define QueAPIExport 
#else 
#define QueAPIExport __declspec(dllimport) 
#endif 

#ifdef __cplusplus 
extern "C" { 
#endif 

typedef uint32 QuePointHandle; 

QueAPIExport QueErrT16 QueCreatePointFromAddress 
    (
    QueSelectAddressType* addr, // in: Address data to search on. 
    QuePointHandle*   point // out: Handle to selected point. Must be closed with QueClosePoint. 
    ); 

Вот как я определил DllImport:

[DllImport("QueAPI.DLL", EntryPoint = "QueCreatePointFromAddress")] 
public static unsafe extern QueTypesnConst.QueErrT16 QueCreatePointFromAddress(QueTypesnConst.QueSelectAddressType *address, uint *point); 

EDIT2: Решения проблемы были следующими кодовыми блоками: Для конструкций:

[StructLayout(LayoutKind.Sequential)] 
public struct QueSelectAddressType 
{ 
    [MarshalAsAttribute(UnmanagedType.LPWStr)] 
    public string streetAddress; 
    [MarshalAsAttribute(UnmanagedType.LPWStr)] 
    public string city; 
    [MarshalAsAttribute(UnmanagedType.LPWStr)] 
    public string state; 
    [MarshalAsAttribute(UnmanagedType.LPWStr)] 
    public string country; 
    [MarshalAsAttribute(UnmanagedType.LPWStr)] 
    public string postalCode; 
}; 

[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Unicode)] 
public struct QueAddressType 
{ 
    [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst=51)] 
    public string streetAddress; 
    [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 51)] 
    public string city; 
    [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 51)] 
    public string state; 
    [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 51)] 
    public string country; 
    [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 12)] 
    public string postalCode; 
}; 

Для DllImport:

[DllImport("QueAPI.DLL", EntryPoint = "QueCreatePointFromAddress")] 
public static extern QueTypesnConst.QueErrT16 QueCreatePointFromAddress(ref QueTypesnConst.QueSelectAddressType address, ref uint point); 
+0

Вы заботитесь о размерах или вы можете просто использовать строку? – ChaosPandion

+1

Я действительно верю, что размеры имеют значение, но я не могу быть уверен – 2010-02-08 19:16:16

ответ

7

Попробуйте следующее определение

public partial class NativeConstants { 

    /// QUE_ADDR_BUF_LENGTH -> 50 
    public const int QUE_ADDR_BUF_LENGTH = 50; 

    /// QUE_POST_BUF_LENGTH -> 11 
    public const int QUE_POST_BUF_LENGTH = 11; 
} 

[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] 
public struct QueSelectAddressType { 

    /// WCHAR* 
    [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)] 
    public string streetAddress; 

    /// WCHAR* 
    [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)] 
    public string city; 

    /// WCHAR* 
    [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)] 
    public string state; 

    /// WCHAR* 
    [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)] 
    public string country; 

    /// WCHAR* 
    [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)] 
    public string postalCode; 
} 

[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet=System.Runtime.InteropServices.CharSet.Unicode)] 
public struct QueAddressType { 

    /// WCHAR[51] 
    [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=51)] 
    public string streetAddress; 

    /// WCHAR[51] 
    [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=51)] 
    public string city; 

    /// WCHAR[51] 
    [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=51)] 
    public string state; 

    /// WCHAR[51] 
    [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=51)] 
    public string country; 

    /// WCHAR[12] 
    [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=12)] 
    public string postalCode; 
} 
+0

@ JaredPar: вам может потребоваться включить SizeConst в атрибуты ... т. Е. SizeConst = NativeConstants.QUE_ADDR_BUF_LENGTH – t0mm13b

+0

@ tommieb75, он включает модификатор SizeConst на нужную ему структуру. Вы должны прокрутить вправо из-за невероятно длинного кода. – JaredPar

+0

Я сделал редактирование оригинального сообщения, что может помочь в определении ответа. – 2010-02-08 19:40:08

0
public struct QueSelectAddressType 
{ 
    public readonly string StreetAddress; 
    public readonly string City; 
    public readonly string State; 
    public readonly string Country; 
    public readonly string PostalCode; 

    public QueSelectAddressType(string street, string city, string state, string country, string code) 
{ 
    this.StreetAddress = street; 
    this.City = city; 
    this.State = state; 
    this.Country = country; 
    this.PostalCode = code; 
} 
} 

public struct QueAddressType 
{ 
    char[] streetAddress = new char[QUE_ADDR_BUF_LENGTH + 1]; 
    char[] city = new char[QUE_ADDR_BUF_LENGTH + 1]; 
    char[] state = new char[QUE_ADDR_BUF_LENGTH + 1]; 
    char[] country = new char[QUE_ADDR_BUF_LENGTH + 1]; 
    char[] postalCode = new char[QUE_POST_BUF_LENGTH + 1]; 
} 
+1

@taylonr: Я не думаю, что это сработает, поскольку у вас не может быть инициализатор в структуре ... – t0mm13b

+0

Не уверен, MSDN (http://msdn.microsoft.com/en-us/library/aa288208(VS. 71) .aspx) просто говорит: У структуры не может быть инициализатор в форме: base (список-аргумент). Но я этого не делаю. Конечно, выше, чем JaredPar, лучше ... Я думаю, он подал, когда я печатал – taylonr

 Смежные вопросы

  • Нет связанных вопросов^_^