从不同智能合约访问合约内的mapping

  • Post author:
  • Post category:其他


我们在写合约的时候,经常会遇到,一个solidity智能合约访问另一个智能合约的mapping数据,这里有两种方案

①第一种方案如下面代码

②  第二种方案就是在被访问合约中写读取mapping里面数据的方法,然后在访问者合约写interface接口

pragma solidity ^0.4.6;

//被访问合约
contract Product{ 

  struct ProductStruct {  
    bytes32 name;  //string是一个不能在合约之间传递的可变长度字段
    bool status;  
  }  

  mapping(uint => ProductStruct) public productStructs;

  function updateProduct(bytes32 name, uint ID) returns(bool success) {

  // following seems more like the intent. p[ID].n isn't valid

    productStructs[ID].name = name;
    productStructs[ID].status = true;
    return true;
  }
}

//外部访问者合约

contract External {

  Product p;

  function External(address addr) {
    p = Product(addr);
  }

  function readProduct(uint u) constant returns(bytes32 name, bool status) {
    return(p.productStructs(u));
  }
}

参考链接:

solidity – Accessing a public mapping within a contract from a different contract – Ethereum Stack Exchange



版权声明:本文为weixin_39842528原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。