我正在用C库制作消息传递系统。

为了从C库(DLL)发送消息,我制作了这个DLL文件,并尝试从C回调到C#

这是C DLL代码

日志记录

#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));


日志记录

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


C#中的Program.cs

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


在控制台中,我可以看到该消息,但是有关函数指针的错误。

c# - 使用char从C DLL进行C#回调*-LMLPHP

我不明白这是什么错误,我想知道如何调试以及如何在C#和C之间设置参数,指针。

最佳答案

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

关于c# - 使用char从C DLL进行C#回调*,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41563998/

10-15 02:11
查看更多