EOS 合约中的 eosio::name 和 std::string 之间的转换

yufei       5 年, 4 月 前       1191

EOS 合约开发中的 eosio::namestd::string 之间的转换的规则如下:

eosio::name -> std::string

eosio:name from = "hello"_n;

// eosio::name -> std::string
auto username         = eosio::name{from};
std::string from_name = username.to_string();

std::string -> eosio::name

std::string username  = "hello";

// 1
eosio::name from = name(username);

// 2
eosio::name from = "hello"_n;

我们写一个范例来演示一下

hello.cpp

#include<eosiolib/eosio.hpp>
using namespace eosio;


class [[eosio::contract]] hello: eosio::contract {
public:
    using eosio::contract::contract;
    [[eosio::action]] void hi(){

        eosio:name from = "hello"_n;

        // eosio::name -> std::string
        auto username         = eosio::name{from};
        std::string from_name = username.to_string();
        print("eosio::name --> std::string:");
        print(from_name);
        print("    ");


        std::string username2  = "hello";
        // 1
        eosio::name from2 = name(username2);
        // 2
        eosio::name from3 = "hello"_n;
        print("std::string --> eosio::name:");
        print(from2);
    }
};

EOSIO_DISPATCH(hello,(hi))

编译

eosio-cpp -o hello.wasm hello.cpp --abigen

部署

cleos set contract hello ../hello -p hello@active

运行结果如下

cleos push action hello hi '[]' -p hello@active
executed transaction: 5f4a06ae0a4c5661cd307ca423636ace12359a73adc71c3751b5b6552baeada8  96 bytes  1522 us
#         hello <= hello::hi                    ""
>> eosio::name --> std::string:hello    std::string --> eosio::name:hello
目前尚无回复
简单教程 = 简单教程,简单编程
简单教程 是一个关于技术和学习的地方
现在注册
已注册用户请 登入
关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.