简体   繁体   中英

c# callback from C DLL with char *

I'm making messaging system with C library.

To send messages from C library (DLL), I made this DLL file and tried to callback from C to C#

here is C DLL Code

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 in 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);
        }
    }
}

And in console I could see the message, but there was a error about function pointer.

在此处输入图片说明

I didn't understand what error was and I wonder how to debug and how to set parameters, pointers between C# and C.

您已将DllImport语句声明为CallingConvention = CallingConvention.StdCall但是在C代码中将其声明为__declspec ,则需要在所有导入上使用CallingConvention = CallingConvention.Cdecl (如果未指定,则默认为CallingConvention.Winapi ,在大多数平台上都映射到StdCall )。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM