2013-03-13 66 views
0

我需要关于从C函数向TCL调用函数发送字符串列表的指导。我可以通过swig和函数返回值的帮助,将C函数中的整数,浮点值列表发送回TCL过程。但是我无法发送像“test1”,“test2”这样的字符串列表,从swig中返回TCL procs以及返回值。任何指导/指针都会很棒。使用Swig从C函数向TCL过程发送字符串列表

那就是工作的代码是这样的

int addsub (int a, int b, int *result1, int *result2) { 
    *result1 = a + b; 
    *result2 = a - b; 
    printf("\n The value is: %i, %i \n",*result1, *result2); 
    return 8; 
} 

痛饮接口样子

%apply int *OUTPUT {int *result1, int *result2}; 

TCL呼叫就像

tclsh 
% Addsub 10 5 

8 15 5. 

它给结果输出作为一个列表

但是,当我试图做类似的事情在一个字符串在TCL返回列表只返回字符串中的第一个字符

代码不起作用

int test_str (char *out1, char *out2) { 
    char *str1, *str2; 
    str1 = "Test1"; 
    str2 = "Test2"; 
    strcpy (out1,str1); 
    strcpy (out2,str2); 
    printf ("Out 1 is %s\n", out1); 
    printf ("Out 2 is %s\n", out2); 
    return 100; 
} 

痛饮接口文件看起来像

%apply int *OUTPUT {char *out1, char *out2}; 

TCL呼叫就像

Tclsh 

% Teststr 

Out 1 is est2 
Out 2 is Test2 
100 101 84 

它不给整个海峡ING。给出字符串中第一个字母的ASCII值。

或者,如果我的C函数是这样

int test_str (char *out1, char *out2) { 
    char *str1,*str2; 
    str1 ="Test1"; 
    str2 = "Test2"; 
    out1=str1; 
    out2=str2; 
    //strcpy (out1,str1); 
    //strcpy (out2,str2); 
    printf ("String 1 is %s\n", str1); 
    printf ("String 2 is %s\n", str2); 
    printf ("Out 1 is %s\n", out1); 
    printf ("Out 2 is %s\n", out2); 
    return 100; 
} 

痛饮接口文件看起来像

%apply int *OUTPUT {char *out1, char *out2}; 

tclsh的

% test_str 

String 1 is Test1 
String 2 is Test2 
Out 1 is Test1 
Out 2 is Test2 
100 0 -127 

有人能说出这到底是怎么失踪。

回答

1

这是一个非常棘手的案例。在处理用于输出的变量char *时,SWIG会遇到特殊问题;只有太多的缺失信息才能够找出需要自动执行的所有事情。 (我认为它最终把他们当作一个长度为1的字符数组在默认情况下,这是不是非常有帮助。)

您需要指定一个argout typemap(和助手in类型映射)来解决这个问题:

// Allocate a (short) working buffer for the string; this is the part that 
// SWIG *cannot* guess for you. 
%typemap(in, numinputs=0) char *OUTPUT (char temp[50]) { 
    $1 = &temp; 
} 
// Actually how to do the mapping of strings from a local buffer into Tcl values 
%typemap(tcl,argout) char * { 
    $result = Tcl_NewStringObj($1, -1); 
} 

然后您必须%apply才能在正确的值上获得缓冲区分配。 (请注意,通过这种方式获得缓冲区管理是非常棘手的,您正在使用的函数签名并不适合做好它的工作。)


你最后一个例子根本不起作用;你没有通过任何机制返回值(由于C字符串的工作方式;你只是在你的函数内部设置东西,而不是告诉调用者)。字符串不是实际上复制除非你做strcpy ...

+0

感谢您的回应。你能让我知道如何申请%。 – user2165910 2013-03-14 12:36:06

+0

所以你建议使用strcpy机制来做到这一点。但是如果你看到TCL打印时第一个变量的第一个字符丢失了。当你说这是非常棘手的,这是否是其他方式做这个,因为我需要多次使用相同的机制从C函数获取字符串并在我的TCL代码中使用 – user2165910 2013-03-14 12:45:32

+0

@user我认为你是做'%应用'权利,虽然我并不确定。问题部分原因在于'char *'只是指向''char'(字符串就是约定),部分原因你不清楚代码中的调用约定是什么。关键问题:什么规模的缓冲区?谁分配缓冲区?你的被调用的代码如何知道这个东西?这些东西都需要得到'%typemap'的权利...... – 2013-03-14 13:59:30