2017-01-10 69 views
0

我正在使用C庫進行消息傳遞系統。C#C DLL回調char *

從C庫(DLL)發送郵件,我做了這個DLL文件,並試圖從C到C#

這裏回調是C DLL的代碼

logging.h

#pragma once 

#include <stdio.h> 

struct loggingMessage { 
    void (*fp)(char *, int, int); 
}; 

struct loggingMessage messageConfig; 

__declspec(dllexport) void loggingInitialize(); 

__declspec(dllexport) void print(); 

__declspec(dllexport) void setEventCallBack(void(*fp)(char *, int, int)); 

logging.c

void loggingInitialize() 
{ 
    messageConfig.fp = NULL; 
} 

void print(char *str, int length) 
{ 
    char buf[1024]; 
    memset(buf, 0, sizeof(char) * 1024); 

    sprintf(buf, "%s", str); 

    if (messageConfig.fp != NULL) 
    { 
     messageConfig.fp(buf, length, 0); 
    } 
} 

void setEventCallBack(void (*fp)(char *buf, int length, int debugLevel)) 
{ 
    messageConfig.fp = fp; 
    char str[512] = "stringTmp"; 
    fp(str, 1, 0); 
    fp(str, 1, 1); 
    fp(str, 1, 2); 
    fp(str, 1, 3); 
} 

Program.cs的在C#

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Runtime.InteropServices; 
using System.Text; 
using System.Threading.Tasks; 

delegate void EventCallback(string _input, int length, int level); 

namespace console 
{ 
    class Program 
    { 
     [DllImport("logging.dll", CallingConvention = CallingConvention.StdCall)] 
    public static extern void print(); 

     [DllImport("logging.dll")] 
    public static extern void setEventCallBack(EventCallback fp); 

     [DllImport("logging.dll")] 
    public static extern void loggingInitialize(); 

    public static void update(string _input, int length, int level) 
     { 
      Console.WriteLine("Message : {0} Length {1} Level {2}", _input, length , level); 
     } 

     static void Main(string[] args) 
     { 
      loggingInitialize(); 
      setEventCallBack(update); 
     } 
    } 
} 

而在控制檯中,我可以看到該消息,但是存在關於函數指針的錯誤。

enter image description here

我不明白的是,我不知道是什麼錯誤如何調試和如何設置參數,C#和C之間的指針

+0

Stack Overflow是編程和開發問題的網站。這個問題似乎與題目無關,因爲它不涉及編程或開發。請參閱幫助中心的[我可以詢問哪些主題](http://stackoverflow.com/help/on-topic)。也許[超級用戶](http://superuser.com/)或[Unix&Linux堆棧交換](http://unix.stackexchange.com/)會是一個更好的地方。另請參閱[我在哪裏發佈有關Dev Ops的問題?](http://meta.stackexchange.com/q/134306) – jww

回答

1

在你宣佈你的DllImport陳述CallingConvention = CallingConvention.StdCall但是你C代碼聲明它們爲__declspec,則需要在所有導入中使用CallingConvention = CallingConvention.Cdecl(如果未指定,則默認爲CallingConvention.Winapi,其映射到大多數平臺上的StdCall)。