相同功能的两个名称 [英] Two names for the same function

查看:87
本文介绍了相同功能的两个名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要两个具有相同功能的实例(不仅仅是别名).绝对有效的一件事是

I need two instances of the same function (not just alias). One thing that definitely works is

void writedata(union chip *tempchip, unsigned char *datapos, int datanum)
{
   blahblah
}

void writestring(union chip *tempchip, unsigned char *datapos, int datanum)
{
   writedata(tempchip, datapos, datanum);
}

这有点愚蠢,因为第二个参数只是将参数传递给第一个参数.所以我试图变得聪明".并制作一个指针

This is kind of silly, because the second just passes parameters to the first. So I tried to be "smart" and make a pointer

void writedata(union chip *tempchip, unsigned char *datapos, int datanum)
{
   blahblah
}

void (* writestring)(union chip *, unsigned char *, int) = writedata;

使用时会返回细分错误.为什么第二种方法不起作用?

which on using returns segmentation error. Why is the second method not working?

我正在通过 ctypes Python 调用这两个函数:

I am calling both functions from Python via ctypes:

writedata = parallel.writedata
writedata.argtypes = [devpointer, POINTER(c_ubyte), c_int]

writestring = parallel.writestring
writestring.argtypes = [devpointer, c_char_p, c_int]

因为我想同时提供 string s和 byte array s作为第二个参数.

because I want to supply both strings and byte arrays as the second argument.

推荐答案

我认为您只是想传递与单个函数不同的数据,例如

I think you just want to pass data different was to a single function, such as this other question you asked. The solution is to use a c_void_p on the Python side to accept different kinds of pointers. The C code will receive the pointer and treat it as unsigned char *.

这是一个仅用于解决问题的DLL示例:

Here's a sample DLL which just focuses on the problem:

test.c

#include <stdio.h>

__declspec(dllexport)
void func(unsigned char *datapos, size_t length)
{
    for(int i = 0; i < length; ++i)
        printf("%02hhx ",datapos[i]);
    printf("\n");
}

test.py

from ctypes import *

dll = CDLL('./test')
_func = dll.func
_func.argtypes = c_void_p,c_size_t
_func.restype = None

def func(data):
    _func(data,len(data))

test1 = b'\x01\x02\x03'
test2 = (c_ubyte*3)(1,2,3)

func(test1)
func(test2)

输出:

01 02 03
01 02 03

这篇关于相同功能的两个名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆