Caffe2 - C++ API
A deep learning, cross platform ML framework
tutorial_blob.cc
1 
17 #include "caffe2/core/blob.h"
18 #include "caffe2/core/init.h"
19 #include "caffe2/core/tensor.h"
20 #include "caffe2/core/logging.h"
21 
22 // We will be lazy and just use the whole namespace.
23 using namespace caffe2;
24 
25 
26 int main(int argc, char** argv) {
27  caffe2::GlobalInit(&argc, &argv);
28  caffe2::ShowLogInfoToStderr();
29 
30  LOG(INFO) <<
31  "This script corresponds to the Blob part of the Caffe2 C++ "
32  "tutorial.";
33 
34  LOG(INFO) << "Let's create a blob myblob.";
35 
36  Blob myblob;
37 
38  LOG(INFO) << "Let's set it to int and set the value to 10.";
39 
40  int* myint = myblob.GetMutable<int>();
41  *myint = 10;
42 
43  LOG(INFO)
44  << "Is the blob type int? "
45  << myblob.IsType<int>();
46 
47  LOG(INFO)
48  << "Is the blob type float? "
49  << myblob.IsType<float>();
50 
51  const int& myint_const = myblob.Get<int>();
52  LOG(INFO)
53  << "The value of the int number stored in the blob is: "
54  << myint_const;
55 
56  LOG(INFO)
57  << "Let's try to get a float pointer. This will trigger an exception.";
58 
59  try {
60  const float& myfloat = myblob.Get<float>();
61  LOG(FATAL) << "This line should never happen.";
62  } catch (std::exception& e) {
63  LOG(INFO)
64  << "As expected, we got an exception. Its content says: "
65  << e.what();
66  }
67 
68  LOG(INFO) <<
69  "However, we can change the content type (and destroy the old "
70  "content) by calling GetMutable. Let's change it to double.";
71 
72  double* mydouble = myblob.GetMutable<double>();
73  *mydouble = 3.14;
74 
75  LOG(INFO) << "The new content is: " << myblob.Get<double>();
76 
77  LOG(INFO) <<
78  "If we have a pre-created object, we can use Reset() to transfer the "
79  "object to a blob.";
80 
81  std::string* pvec = new std::string();
82  myblob.Reset(pvec); // no need to release pvec, myblob takes ownership.
83 
84  LOG(INFO) << "Is the blob now of type string? "
85  << myblob.IsType<std::string>();
86 
87  LOG(INFO) << "This concludes the blob tutorial.";
88  return 0;
89 }
Blob is a general container that hosts a typed pointer.
Definition: blob.h:24
bool IsType() const noexcept
Checks if the content stored in the blob is of type T.
Definition: blob.h:47
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...
Definition: blob.h:13
T * Reset(T *allocated)
Sets the underlying object to the allocated one.
Definition: blob.h:132
T * GetMutable()
Gets a mutable pointer to the stored object.
Definition: blob.h:100
bool GlobalInit(int *pargc, char ***pargv)
Initialize the global environment of caffe2.
Definition: init.cc:44
const T & Get() const
Gets the const reference of the stored object.
Definition: blob.h:71