将字符串内存转换为字符串calldata?

use*_*110 3 ethereum solidity

想知道是否可以在字符串内存和字符串 calldata 之间进行转换,以便使用仅适用于字符串 calldata 的 string[start : end] 形式的索引。这个功能似乎有效:

function splice(string calldata source, int startPos, int numchars) public pure returns(string memory) {
        if (startPos > int(length(sourcestring))) return "";
        int start = startPos -1;
        int end = startPos + (numchars -1);
        string memory retval = string(source[uint(start) : uint(end)]);
        return retval;

    }
Run Code Online (Sandbox Code Playgroud)

但是如果我将参数更改source为字符串内存,则会出现错误 ,因为显然获取子字符串的string memory retval = string(source([uint(start) : uint(end)]) 形式适用于字符串而不是字符串,并且没有明显的方法将 a 转换为 a 。sourcestring[start : end]calldatamemorystring memorystring calldata

有什么办法可以做到这一点吗?

cam*_*eel 5

呼叫数据是只读的。您可以将 calldata 变量解码到内存中,但反之则不然。

不幸的是,数组切片仅针对 calldata 实现。对于内存和存储来说,它有点复杂,并且尚未实现(请参阅问题#7423)。

您的情况的解决方法是逐个复制字符,这实际上是编译器在幕后所做的事情,因为您试图从公共函数返回切片(这会将切片具体化为数组)。