Импорт структуры C в программу C # - PullRequest
1 голос
/ 19 июня 2019

Sctruct

Я не большой программист на C # или C и не нашел большого руководства по определению указателей и структур в структуре.Я пытаюсь импортировать следующее из Cll dll в программу на C #:

#define MAXFILENAME     259 

struct IDentry {
    char* IDname;
    int length;
};
typedef struct IDentry idEntry;


struct SMOutputAPI {
    char name[MAXFILENAME + 1];     
    FILE* file;                     

    struct IDentry *elementNames;   

    long Nperiods;                  
    int FlowUnits;                  

    int Nsubcatch;                  
    int Nnodes;                     
    int Nlinks;                     
    int Npolluts;                   

    int SubcatchVars;               
    int NodeVars;                   
    int LinkVars;                   
    int SysVars;                    

    double StartDate;               
    int    ReportStep;              

    __int64 IDPos;                  
    __int64 ObjPropPos;             
    __int64 ResultsPos;               
    __int64 BytesPerPeriod;           
};

Я не уверен, как обрабатывать свойства *elementsNames, file или name.То, что я до сих пор имею в C #:

int MAXFILENAME = 259 

[StructLayout(LayoutKind.Sequential)]
public struct SMOutputAPI
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = MAXFILENAME+1)]
    public string name;

    IntPtr file;

    IntPtr elementNames;

    public long Nperiods;   
    public int FlowUnits;   

    public int Nsubcatch;   
    public int Nnodes;      
    public int Nlinks;      
    public int Npolluts;    

    public int SubcatchVars;
    public int NodeVars;    
    public int LinkVars;    
    public int SysVars;     

    public double StartDate;
    public int ReportStep;  

    public int IDPos;       
    public int ObjPropPos;              
    public int ResultsPos;              
    public int BytesPerPeriod;          
};

Приложение C # строится нормально, но когда я вызываю функцию инициализации C, которая должна вернуть новую структуру SMOutputAPI, я получаю ошибку:

System.Runtime.InteropServices.MarshalDirectiveException 
Method's type signature is not PInvoke compatible. 

Будем весьма благодарны за любые мысли о том, как правильно указать эту структуру в C #.Спасибо!

Инициализация структуры

Структура инициализируется в c-коде с помощью:

SMOutputAPI* DLLEXPORT SMO_init(void)
//
//  Purpose: Returns an initialized pointer for the opaque SMOutputAPI
//    structure.
//
{
    SMOutputAPI *smoapi = malloc(sizeof(struct SMOutputAPI));
    smoapi->elementNames = NULL;

    return smoapi;
}

Соответствующий код c #:

[DllImport("swmm-output.dll")]
static extern SMOutputAPI SMO_init();


static void Main(string[] args)
{
    Console.Write("Hello World!");

    SMOutputAPI SMO = SMO_init();
}
...