如何在Metal内核中的C ++参考或指针上访问成员?

问题描述 投票:4回答:1

当尝试实际使用来自任何地址空间(常量,设备或线程)的引用时,我总是会遇到相同的错误。这不会编译,并给出一个奇怪的错误:

struct Foo {
    int getter() const {
        return 1;
    }
};

void use_foo(constant Foo& foo) {
    int x = foo.getter(); // error here
}

kernel void test_kernel(constant Foo& foo [[buffer(0)]]) {
    use_foo(foo);
}

错误是:

无法使用类型为'const constant Foo'的表达式来初始化'const Foo'类型的对象参数

用其他任何存储器地址说明符替换constant,这是相同的一般错误。不管是直接传递给内核的引用还是函数创建的线程本地引用都无所谓-由于此错误,我实际上无法以任何方式使用这些引用。它们是const引用还是非const引用也没有区别。

唯一的解决方法是仅复制Foo,而不是尝试使用对其的引用。我从未理解过这种奇怪的错误。我也尝试过将参数设为constant const Foo&以及其他试验和错误。

任何人都可以建议如何实际使用参考吗?

如果切换到使用指针而不是引用,则会出现类似的错误:

enter image description here

来自此:

struct Foo {
    int getter() const {
        return 1;
    }
};

void use_foo(constant const Foo* const foo) {
    int x = foo->getter(); // error here
}

kernel void test_kernel(constant Foo* foo [[buffer(0)]]) {
    use_foo(foo);
}

类似尝试在不同地方使用const的尝试没有区别。

c++ ios gpu metal
1个回答
3
投票

您的member function's qualifications通常必须与被调用者对象的类型匹配。如果要在const constant对象上调用这种方法,则可以这样对方法进行限定:

    int getter() const constant {
        return 1;
    }

Metal Shading Language Specification说(§4):“必须使用[device,constant,thread,threadgroup或threadgroup_imageblock]声明为指针或引用的任何变量]”。重要的是要了解成员函数的this参数是一个指针(基本上是一个不可见的函数参数),并且函数的限定条件会影响该指针的类型。实际上,您是在声明int getter(const constant Foo* this)

© www.soinside.com 2019 - 2024. All rights reserved.