2012-10-06 162 views
2

可以通过参数传递结构吗?通过LLVM参数传递结构

它与C abi兼容吗?

[编辑]

基本上,我想有一个C++ POD其中将包括两个构件(结构将是一个脂肪指针,用指针和一个整数),并能够通过这个结构作为调用指令中的函数参数(即使调用C代码时)。

我现在没有使用胖指针(指针和整数都在不同的函数参数中),我想知道在启动一个相当大的重构之前是否有可能!

+0

请详细说明。你有什么尝试?你可以包含一些代码吗? –

+0

@SimonGermain我添加了一些关于我的用例的上下文。目前没有代码。 –

回答

0

绝对可以。这里有一个例子:

struct MyStruct_t { 
    char *charPointer; 
    int number; 
}; 

void myFunction(MyStruct_t myStructAsParam) { 

    printf("String: %s, Number: %i", myStructAsParam.charPointer, myStructAsParam.number); 
    // Your stuff here. 
} 
+0

您的myStructAsParam是一个指针,但您使用'。'运营商,什么是正确的事情?要清楚,我正在寻找传递myStructAsParam作为值,而不是指针(http://codepad.org/H4Az2uKK)。 –

+0

哎呀,习惯的力量:P –

1

你可以这样做。

你可以找出LLVM代码是什么样品C通过复制和粘贴http://llvm.org/demo/index.cgi C代码为LLVM的在线演示。

如果您复制并在codepad.org在粘贴代码,你会发现LLVM生成myFunction的以下内容:

define void @_Z10myFunction10MyStruct_t(i8* %myStructAsParam.coerce0, i32  %myStructAsParam.coerce1) nounwind uwtable { 
    %1 = tail call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([23 x i8]* @.str, i64 0, i64 0), i8* %myStructAsParam.coerce0, i32 %myStructAsParam.coerce1) 
    ret void 
} 

当然,如果你看一下叫你会发现,没有副本正在制作。这取决于调用函数。如果我们写一个小C函数:

void myCallingFunction(MyStruct_t *foobar) 
{ 
    myFunction(*foobar); 
} 

我们可以看到,对于myCallingFunction产生的LLVM位码为:

define void @_Z17myCallingFunctionP10MyStruct_t(%struct.MyStruct_t* nocapture %foobar) nounwind uwtable { 
    %foobar.0 = getelementptr inbounds %struct.MyStruct_t* %foobar, i64 0, i32 0 
    %tmp = load i8** %foobar.0, align 8 
    %foobar.1 = getelementptr inbounds %struct.MyStruct_t* %foobar, i64 0, i32 1 
    %tmp1 = load i32* %foobar.1, align 8 
    %1 = tail call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([23 x i8]* @.str, i64 0, i64 0), i8* %tmp, i32 %tmp1) nounwind 
    ret void 
} 

调用功能,使该结构的一个副本,然后通过在地址的副本。