You can use the following Code for it:
pragma solidity ^0.4.18;
contract Test {
uint256 public val = 256;
}
contract Other {
Test testContract;
function setAddress(address _address) {
testContract = Test(_address);
}
function getVal() constant public returns (uint256) {
return testContract.val();
}
}
You need to define a variable which is of type Test
. Than you can get the value of val
by calling its getter function val()
which is automatically generated due to the public
keyword.
EDIT:
If you want to make variable val
private and only accessible for the Other
contract you should provide a getter function like the following:
function getVal() public returns (uint) {
return val;
}
Now you can set the permissions for getVal()
so that only addresses who may access val
will have permissions to read it.
Hope it helps.
EDIT 2:
This is a complete code snippet for keeping the variable val
private and only allow Other
contract to read it:
pragma solidity ^0.4.18;
contract Test {
address owner;
uint256 val = 256;
address otherContract;
function Test(){
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyOtherContract() {
require(msg.sender == otherContract);
_;
}
function setOtherContract(address _otherContract) onlyOwner {
otherContract = _otherContract;
}
function getVal() onlyOtherContract returns (uint) {
return val;
}
}
contract Other {
Test testContract;
function setAddress(address _address) {
testContract = Test(_address);
}
function getVal() constant public returns (uint256) {
return testContract.getVal();
}
}
Try the following steps:
- Deploy
Test
contract
- Deploy
Other
contract
- Set
testContract
in Other
contract with the setAddress
function
- Set the
otherContract
variable in the Test
contract with the setOtherContract
function
- Call the
getVal
function in the Other
contract.
Now you can also try to call the getVal
function in the Test
contract directly and you will see, that your call is reverted. This is because after step 4 only the Other
contract is allowed to call getVal
.
Kind regards